2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.collect.Sets;
24 import fj.data.Either;
25 import org.apache.commons.collections.CollectionUtils;
26 import org.apache.commons.collections.MapUtils;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
30 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
31 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
32 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
33 import org.openecomp.sdc.be.components.impl.utils.DirectivesUtils;
34 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
35 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
36 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
37 import org.openecomp.sdc.be.components.validation.ComponentValidations;
38 import org.openecomp.sdc.be.config.BeEcompErrorManager;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
40 import org.openecomp.sdc.be.config.ConfigurationManager;
41 import org.openecomp.sdc.be.dao.api.ActionStatus;
42 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
43 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
44 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
45 import org.openecomp.sdc.be.datamodel.utils.ContainerInstanceTypesData;
46 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
49 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
54 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
55 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
56 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
57 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
58 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
59 import org.openecomp.sdc.be.impl.ServiceFilterUtils;
60 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
61 import org.openecomp.sdc.be.model.ArtifactDefinition;
62 import org.openecomp.sdc.be.model.CapabilityDefinition;
63 import org.openecomp.sdc.be.model.Component;
64 import org.openecomp.sdc.be.model.ComponentInstance;
65 import org.openecomp.sdc.be.model.ComponentInstanceInput;
66 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
67 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
68 import org.openecomp.sdc.be.model.ComponentParametersView;
69 import org.openecomp.sdc.be.model.DataTypeDefinition;
70 import org.openecomp.sdc.be.model.GroupDefinition;
71 import org.openecomp.sdc.be.model.InputDefinition;
72 import org.openecomp.sdc.be.model.InterfaceDefinition;
73 import org.openecomp.sdc.be.model.LifecycleStateEnum;
74 import org.openecomp.sdc.be.model.PolicyDefinition;
75 import org.openecomp.sdc.be.model.PropertyDefinition;
76 import org.openecomp.sdc.be.model.RelationshipInfo;
77 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
78 import org.openecomp.sdc.be.model.RequirementDefinition;
79 import org.openecomp.sdc.be.model.Resource;
80 import org.openecomp.sdc.be.model.Service;
81 import org.openecomp.sdc.be.model.User;
82 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
83 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation;
84 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
85 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
86 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
87 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
88 import org.openecomp.sdc.be.model.operations.StorageException;
89 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
90 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
91 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
92 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
93 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
94 import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
95 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
96 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
97 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
98 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
99 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
100 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
101 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
102 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
103 import org.openecomp.sdc.common.api.Constants;
104 import org.openecomp.sdc.common.datastructure.Wrapper;
105 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
106 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
107 import org.openecomp.sdc.common.log.wrappers.Logger;
108 import org.openecomp.sdc.common.util.ValidationUtils;
109 import org.openecomp.sdc.exception.ResponseFormat;
110 import org.springframework.beans.factory.annotation.Autowired;
112 import java.util.ArrayList;
113 import java.util.Arrays;
114 import java.util.Collection;
115 import java.util.Collections;
116 import java.util.HashMap;
117 import java.util.Iterator;
118 import java.util.List;
119 import java.util.Map;
120 import java.util.Map.Entry;
121 import java.util.Objects;
122 import java.util.Optional;
123 import java.util.Set;
124 import java.util.UUID;
125 import java.util.function.BiConsumer;
126 import java.util.stream.Collectors;
128 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
129 import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityOfChildInstance;
131 @org.springframework.stereotype.Component
132 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
134 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class.getName());
135 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
136 private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
137 private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
138 private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
139 {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
140 private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
141 private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
142 private static final String INVALID_COMPONENT_TYPE = "invalid component type";
143 private static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
144 private static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
145 private static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
146 private static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
147 private static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
149 private ComponentInstanceOperation componentInstanceOperation;
150 private ArtifactsBusinessLogic artifactBusinessLogic;
151 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
152 private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
153 private ForwardingPathOperation forwardingPathOperation;
154 private NodeFilterOperation serviceFilterOperation;
157 public ComponentInstanceBusinessLogic(IElementOperation elementDao,
158 IGroupOperation groupOperation,
159 IGroupInstanceOperation groupInstanceOperation,
160 IGroupTypeOperation groupTypeOperation,
161 InterfaceOperation interfaceOperation,
162 InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
163 ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
164 ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
165 ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
166 ForwardingPathOperation forwardingPathOperation, NodeFilterOperation serviceFilterOperation,
167 ArtifactsOperations artifactToscaOperation) {
168 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
169 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
170 this.componentInstanceOperation = componentInstanceOperation;
171 this.artifactBusinessLogic = artifactBusinessLogic;
172 this.compInstMergeDataBL = compInstMergeDataBL;
173 this.onChangeInstanceOperationOrchestrator = onChangeInstanceOperationOrchestrator;
174 this.forwardingPathOperation = forwardingPathOperation;
175 this.serviceFilterOperation = serviceFilterOperation;
179 private CompositionBusinessLogic compositionBusinessLogic;
182 private ContainerInstanceTypesData containerInstanceTypesData;
184 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
185 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
188 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
189 List<ComponentInstanceProperty> resList = new ArrayList<>();
190 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
191 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
192 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
194 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
196 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
198 ciName = ciOp.get().getName();
199 if (ciPropList != null && !ciPropList.isEmpty()) {
200 for(ComponentInstanceProperty prop: ciPropList){
201 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
202 addCompInstanceProperty(s, ciName, prop, inputsValues, inputId, resList);
212 private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues, String inputId, List<ComponentInstanceProperty> resList) {
213 if(inputsValues != null && !inputsValues.isEmpty()){
214 for(GetInputValueDataDefinition inputData: inputsValues){
215 if(isGetInputValueForInput(inputData, inputId)){
216 prop.setComponentInstanceId(s);
217 prop.setComponentInstanceName(ciName);
225 public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component,
226 PolicyDefinition policy) {
228 Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
230 if(propertyCandidate.isPresent()) {
231 ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
232 Optional<GetPolicyValueDataDefinition> getPolicyCandidate =
233 getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
235 getPolicyCandidate.ifPresent(getPolicyValue ->
236 updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
237 return Optional.of(componentInstanceProperty);
240 return Optional.empty();
244 private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
245 GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
246 componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
247 List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
248 if(CollectionUtils.isNotEmpty(getPolicyValues)) {
249 getPolicyValues.remove(getPolicyValue);
250 componentInstanceProperty.setGetPolicyValues(getPolicyValues);
251 policyDefinition.setGetPolicyValues(getPolicyValues);
255 private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
256 ComponentInstanceProperty componentInstanceProperty) {
257 List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
258 return getPolicyValues.stream()
259 .filter(getPolicyValue -> getPolicyValue
261 .equals(componentInstanceProperty
266 private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component,
267 PolicyDefinition policy) {
268 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
269 component.getComponentInstancesProperties();
271 if(MapUtils.isEmpty(componentInstancesProperties)) {
272 return Optional.empty();
275 String instanceUniqueId = policy.getInstanceUniqueId();
277 List<ComponentInstanceProperty> componentInstanceProperties =
278 componentInstancesProperties.containsKey(instanceUniqueId)
279 ? componentInstancesProperties.get(instanceUniqueId)
282 return componentInstanceProperties
283 .stream().filter(property -> property.getName().equals(policy.getName())).findAny();
286 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(
287 org.openecomp.sdc.be.model.Component component, String inputId) {
288 List<ComponentInstanceInput> resList = new ArrayList<>();
289 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
290 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
291 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
293 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
295 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
297 ciName = ciOp.get().getName();
298 if (ciPropList != null && !ciPropList.isEmpty()) {
299 for(ComponentInstanceInput prop: ciPropList){
300 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
301 addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
312 private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues, String inputId, List<ComponentInstanceInput> resList) {
313 if(inputsValues != null && !inputsValues.isEmpty()){
314 for(GetInputValueDataDefinition inputData: inputsValues){
315 if(isGetInputValueForInput(inputData, inputId)){
316 prop.setComponentInstanceId(s);
317 prop.setComponentInstanceName(ciName);
325 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
327 Component origComponent = null;
329 org.openecomp.sdc.be.model.Component containerComponent = null;
330 ComponentTypeEnum containerComponentType;
332 user = validateUserExists(userId);
333 validateUserNotEmpty(user, "Create component instance");
334 validateJsonBody(resourceInstance, ComponentInstance.class);
335 containerComponentType = validateComponentType(containerComponentParam);
336 containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
338 if (ModelConverter.isAtomicComponent(containerComponent)) {
339 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
340 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
343 validateCanWorkOnComponent(containerComponent, userId);
345 if (resourceInstance != null && containerComponentType != null) {
346 OriginTypeEnum originType = resourceInstance.getOriginType();
347 validateInstanceName(resourceInstance);
348 if (originType == OriginTypeEnum.ServiceProxy) {
350 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
351 if (isServiceProxyOrigin(serviceProxyOrigin)) {
352 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
354 origComponent = serviceProxyOrigin.left().value();
356 StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
357 if (isFillProxyRes(fillProxyRes)) {
358 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
362 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
364 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
365 validateResourceInstanceState(containerComponent, origComponent);
366 overrideFields(origComponent, resourceInstance);
367 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
369 return createComponent(needLock, containerComponent,origComponent, resourceInstance, user);
371 }catch (ComponentException e){
376 private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) {
378 boolean failed = false;
381 ComponentInstance lockComponent = isNeedLock(needLock, containerComponent);
382 if (lockComponent != null) {
383 return lockComponent;
385 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
386 return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
387 }catch (ComponentException e){
392 unlockComponent(failed, containerComponent);
396 private void overrideFields(Component origComponent, ComponentInstance resourceInstance) {
397 resourceInstance.setComponentVersion(origComponent.getVersion());
398 resourceInstance.setIcon(origComponent.getIcon());
401 private void validateInstanceName(ComponentInstance resourceInstance) {
403 String resourceInstanceName = resourceInstance.getName();
404 if (StringUtils.isEmpty(resourceInstanceName)) {
405 log.debug("ComponentInstance name is empty");
406 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
409 if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
410 log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
411 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
414 if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
415 log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
416 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
420 private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
421 if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT){
422 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
423 containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
427 private void validateOriginAndResourceInstanceTypes(Component containerComponent, Component origComponent, OriginTypeEnum originType) {
428 ResourceTypeEnum resourceType = null;
429 ResourceTypeEnum convertedOriginType;
430 resourceType = getResourceTypeEnumFromOriginComponent(origComponent, resourceType);
431 validateOriginType(originType, resourceType);
432 validateOriginComponentIsValidForContainer(containerComponent, resourceType);
435 private void validateOriginComponentIsValidForContainer(Component containerComponent, ResourceTypeEnum resourceType) {
436 switch (containerComponent.getComponentType()) {
438 if (!containerInstanceTypesData.getServiceContainerList().contains((resourceType))) {
439 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
440 containerComponent.getComponentType().toString(), resourceType.name());
444 if (!containerInstanceTypesData.getValidInstanceTypesInResourceContainer().get(((Resource) containerComponent).getResourceType()).contains(resourceType)) {
445 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
446 containerComponent.getComponentType().toString(), resourceType.name());
450 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
454 private void validateOriginType(OriginTypeEnum originType, ResourceTypeEnum resourceType) {
455 ResourceTypeEnum convertedOriginType;
457 convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
460 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
463 if (resourceType != convertedOriginType) throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
466 private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(Component origComponent, ResourceTypeEnum resourceType) {
467 switch (origComponent.getComponentType()) {
469 resourceType = ResourceTypeEnum.ServiceProxy;
472 resourceType = ((Resource) origComponent).getResourceType();
475 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
480 private ComponentInstance isNeedLock(boolean needLock, Component containerComponent) {
482 lockComponent(containerComponent, "createComponentInstance");
487 private boolean isServiceProxyOrigin(Either<Component, StorageOperationStatus> serviceProxyOrigin) {
488 if (serviceProxyOrigin.isRight()) {
489 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
495 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
496 resourceInstance.setIsProxy(true);
497 ComponentParametersView filter = new ComponentParametersView(true);
498 filter.setIgnoreCapabilities(false);
499 filter.setIgnoreCapabiltyProperties(false);
500 filter.setIgnoreComponentInstances(false);
501 filter.setIgnoreRequirements(false);
502 filter.setIgnoreInterfaces(false);
503 filter.setIgnoreProperties(false);
504 filter.setIgnoreInputs(false);
505 Either<Component, StorageOperationStatus> serviceRes =
506 toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
507 if (serviceRes.isRight()) {
508 return serviceRes.right().value();
510 Component service = serviceRes.left().value();
511 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
512 resourceInstance.setCapabilities(capabilities);
513 Map<String, List<RequirementDefinition>> req = service.getRequirements();
514 resourceInstance.setRequirements(req);
515 Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
516 if(MapUtils.isNotEmpty(serviceInterfaces)) {
517 serviceInterfaces.forEach(resourceInstance::addInterface);
521 resourceInstance.setProperties(PropertiesUtils.getProperties(service));
523 List<InputDefinition> serviceInputs = service.getInputs();
524 resourceInstance.setInputs(serviceInputs);
526 String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
527 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
528 int lastIndexOf = toscaResourceName.lastIndexOf('.');
529 if (lastIndexOf != -1) {
530 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
531 resourceInstance.setToscaComponentName(proxyToscaName);
533 resourceInstance.setName(name);
534 resourceInstance.setIsProxy(true);
535 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
536 resourceInstance.setSourceModelName(service.getName());
537 resourceInstance.setSourceModelUuid(service.getUUID());
538 resourceInstance.setSourceModelUid(service.getUniqueId());
539 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
540 resourceInstance.setDescription("A Proxy for Service " + service.getName());
541 resourceInstance.setComponentVersion(service.getVersion());
543 return StorageOperationStatus.OK;
546 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
548 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
549 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
550 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
552 User user = validateUserExists(userId);
554 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
556 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
558 if (ModelConverter.isAtomicComponent(containerComponent)) {
559 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
560 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
563 validateCanWorkOnComponent(containerComponent, userId);
565 boolean failed = false;
567 lockComponent(containerComponent, "createAndAssociateRIToRI");
568 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
569 Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
571 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
572 ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
573 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
574 associationInfo.setFromNode(resResourceInfo.getUniqueId());
576 associationInfo.setToNode(resResourceInfo.getUniqueId());
579 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponent, containerComponentId, associationInfo);
580 if (resultReqCapDef.isLeft()) {
581 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
582 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
583 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
584 resultOp = Either.left(resInfo);
588 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
589 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
593 }catch (ComponentException e){
597 unlockComponent(failed, containerComponent);
601 private Component getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
602 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
605 private Component getInstanceOriginNode(ComponentInstance componentInstance) {
606 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
609 private Component getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
610 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
611 if (eitherComponent.isRight()) {
612 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
613 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
615 return eitherComponent.left().value();
618 private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
619 Either<ComponentInstance, ResponseFormat> resultOp;
621 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
623 if (result.isRight()) {
624 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
625 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
628 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
629 Component updatedComponent = result.left().value().getLeft();
630 Map<String, String> existingEnvVersions = new HashMap<>();
631 // TODO existingEnvVersions ??
632 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
634 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
635 if (!updatedInstanceOptional.isPresent()) {
636 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
637 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
639 return updatedInstanceOptional.get();
642 public boolean isCloudSpecificArtifact(String artifact) {
643 if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
644 for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
645 if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(str -> artifact.contains(str))) {
657 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
658 * @param containerComponent
659 * @param componentInstance
660 * @param originComponent
662 * @param existingEnvVersions
665 protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) {
667 log.debug("add artifacts to resource instance");
668 List<GroupDefinition> filteredGroups = new ArrayList<>();
669 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
670 if (ActionStatus.OK != status) {
671 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(status, "", null));
673 StorageOperationStatus artStatus;
674 // generate heat_env if necessary
675 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
676 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
678 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
679 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
680 Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
681 .getHeatArtifactDeploymentTimeout().getDefaultMinutes();
682 List<ArtifactDefinition> listOfCloudSpecificArts = new ArrayList<>();
683 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
684 String type = artifact.getArtifactType();
685 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
686 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
688 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())) {
689 artifact.setTimeout(defaultHeatTimeout);
693 if (artifact.checkEsIdExist()) {
694 ArtifactDefinition artifactDefinition = artifactBusinessLogic.createHeatEnvPlaceHolder(new ArrayList<>(),
695 artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
696 NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent,
697 existingEnvVersions);
699 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
701 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
702 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
704 if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) {
705 listOfCloudSpecificArts.add(artifact);
707 if (CollectionUtils.isNotEmpty(filteredGroups)) {
708 filteredGroups.stream().filter(g ->
711 .anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId())))
713 .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
717 groupInstancesArtifacts.forEach((k,v) -> v.addAll(listOfCloudSpecificArts));
718 filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach((e) -> {
719 g.getArtifactsUuid().add(e.getArtifactUUID());
720 g.getArtifacts().add(e.getUniqueId());
722 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
723 if (artStatus != StorageOperationStatus.OK) {
724 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
725 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
728 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
729 if (result != StorageOperationStatus.OK) {
730 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
731 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
733 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
736 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
737 if (artStatus != StorageOperationStatus.OK) {
738 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
739 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
742 componentInstance.setArtifacts(originComponent.getArtifacts());
743 return ActionStatus.OK;
746 private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition, GroupDefinition groupInstance) {
747 List<ArtifactDefinition> artifactsUid;
748 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
749 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
751 artifactsUid = new ArrayList<>();
753 artifactsUid.add(artifactDefinition);
754 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
757 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
758 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts =
759 artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
761 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
762 if (getResourceDeploymentArtifacts.isRight()) {
763 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
764 if (status != StorageOperationStatus.NOT_FOUND) {
765 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
766 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
769 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
772 if (!deploymentArtifacts.isEmpty()) {
773 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
774 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
775 if (!artifact.getValue().checkEsIdExist()) {
776 tempDeploymentArtifacts.remove(artifact.getKey());
780 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
783 return ActionStatus.OK;
786 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
787 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true);
790 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
793 validateUserExists(userId);
795 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
797 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
799 validateCanWorkOnComponent(containerComponent, userId);
800 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
801 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
802 if (validateParentStatus.isRight()) {
803 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
804 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase());
806 if (!validateParentStatus.left().value()) {
807 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
811 lockComponent(containerComponent, "updateComponentInstance");
813 Component origComponent;
814 boolean failed = false;
816 origComponent = getOriginComponentFromComponentInstance(componentInstance);
817 componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
818 }catch (ComponentException e) {
823 unlockComponent(failed, containerComponent);
826 return Either.left(componentInstance);
829 // New Multiple Instance Update API
830 public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
832 boolean failed = false;
834 validateUserExists(userId);
836 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
837 ComponentParametersView componentFilter = new ComponentParametersView();
838 componentFilter.disableAll();
839 componentFilter.setIgnoreUsers(false);
840 componentFilter.setIgnoreComponentInstances(false);
841 if (containerComponent == null) {
842 containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
844 validateCanWorkOnComponent(containerComponent, userId);
846 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
848 for (ComponentInstance componentInstance : componentInstanceList) {
849 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
850 if (!validateParent) {
851 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
852 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
853 containerComponentId);
858 lockComponent(containerComponent, "updateComponentInstance");
861 List<ComponentInstance> updatedList = new ArrayList<>();
862 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
863 List<ComponentInstance> listForUpdate = new ArrayList<>();
864 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
865 containerComponent.setComponentInstances(componentInstanceList);
867 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
868 while (iterator.hasNext()) {
869 ComponentInstance origInst = iterator.next();
870 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
871 if (op.isPresent()) {
872 ComponentInstance updatedCi = op.get();
873 updatedCi = buildComponentInstance(updatedCi, origInst);
875 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
877 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());
878 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
880 listForUpdate.add(updatedCi);
882 listForUpdate.add(origInst);
884 containerComponent.setComponentInstances(listForUpdate);
886 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
887 if (updateStatus.isRight()) {
888 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
889 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
892 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
893 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
894 if (op.isPresent()) {
895 updatedList.add(updatedInstance);
900 }catch (ComponentException e){
905 unlockComponent(failed, containerComponent);
910 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
911 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
914 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
915 if (ComponentTypeEnum.PRODUCT == containerComponentType) {
916 return ComponentTypeEnum.SERVICE_INSTANCE;
918 return ComponentTypeEnum.RESOURCE_INSTANCE;
922 private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
923 ComponentInstance componentInstance) {
925 Optional<ComponentInstance> componentInstanceOptional;
926 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
927 ComponentInstance oldComponentInstance = null;
928 boolean isNameChanged = false;
930 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
931 if (!componentInstanceOptional.isPresent()) {
932 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
933 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
935 String oldComponentName;
936 oldComponentInstance = componentInstanceOptional.get();
937 oldComponentName = oldComponentInstance.getName();
938 String newInstanceName = componentInstance.getName();
939 if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName))
940 isNameChanged = true;
941 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
943 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);
944 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName());
946 if(!DirectivesUtils.isValid(componentInstance.getDirectives())) {
947 final String directivesStr =
948 componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
949 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
950 "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ",
951 oldComponentInstance.getName(), newInstanceName ,
953 throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(), componentInstance.getName()); }
954 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
955 if (updateRes.isRight()) {
956 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
957 updateRes.right().value());
958 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
960 // region - Update instance Groups
962 Either<StorageOperationStatus, StorageOperationStatus> result =
963 toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
964 if (result.isRight())
965 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
967 if (containerComponent instanceof Service){
968 Either<ComponentInstance, ResponseFormat> renameEither =
969 renameServiceFilter((Service) containerComponent, newInstanceName,
970 oldComponentInstance.getName());
971 if (renameEither.isRight()) {
972 throw new ByResponseFormatComponentException(renameEither.right().value());
975 updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
980 String newInstanceId = updateRes.left().value().getRight();
981 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
983 if (!updatedInstanceOptional.isPresent()) {
984 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
985 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
988 return componentInstanceOptional.get();
991 private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
992 Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
993 Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
994 .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName,
995 componentInstance.getName());
996 updated.forEach(fp -> {
997 Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
998 .updateForwardingPath(containerComponent.getUniqueId(), fp);
999 if (resultEither.isRight()){
1000 CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",containerComponent.getName(), resultEither.right().value());
1006 public Either<ComponentInstance, ResponseFormat> renameServiceFilter(Service containerComponent,
1007 String newInstanceName, String oldInstanceName) {
1009 Map<String, CINodeFilterDataDefinition> renamedNodesFilter =
1010 ServiceFilterUtils.getRenamedNodesFilter((Service) containerComponent,
1011 oldInstanceName, newInstanceName);
1012 for( Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()){
1013 Either<CINodeFilterDataDefinition, StorageOperationStatus>
1014 renameEither = serviceFilterOperation.updateNodeFilter(
1015 containerComponent.getUniqueId(),entry.getKey(),entry.getValue());
1016 if (renameEither.isRight()){
1017 return Either.right(componentsUtils.getResponseFormatForResourceInstance(
1018 componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE),
1019 containerComponent.getName(), null));
1023 return Either.left(null);
1028 * The normalized old vf name
1029 * @param newNormailzedPrefix-
1030 * The normalized new vf name
1031 * @param qualifiedGroupInstanceName-
1032 * old Group Instance Name
1034 // modify group names
1035 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
1036 if (qualifiedGroupInstanceName == null) {
1037 log.info("CANNOT change group name ");
1040 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
1041 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
1042 return qualifiedGroupInstanceName;
1045 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
1046 oldComponentInstance.setName(newComponentInstance.getName());
1047 oldComponentInstance.setModificationTime(System.currentTimeMillis());
1048 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
1049 oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
1050 if (oldComponentInstance.getGroupInstances() != null)
1051 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
1052 return oldComponentInstance;
1055 public ComponentInstance deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
1057 validateUserExists(userId);
1059 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1061 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1062 validateCanWorkOnComponent(containerComponent, userId);
1064 boolean failed = false;
1065 ComponentInstance deletedRelatedInst;
1067 if (containerComponent instanceof Service) {
1068 ComponentInstance componentInstance = containerComponent.getComponentInstanceById(componentInstanceId).get();
1069 Either<String, StorageOperationStatus> deleteServiceFilterEither =
1070 serviceFilterOperation.deleteNodeFilter((Service) containerComponent, componentInstanceId);
1071 if (deleteServiceFilterEither.isRight()) {
1072 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(),
1073 containerComponentType);
1074 janusGraphDao.rollback();
1075 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
1077 Either<ComponentInstance, ResponseFormat> resultOp = deleteServiceFiltersRelatedTobeDeletedComponentInstance((Service) containerComponent,
1078 componentInstance, ComponentTypeEnum.SERVICE, userId);
1079 if (resultOp.isRight()) {
1080 janusGraphDao.rollback();
1081 throw new ByResponseFormatComponentException(resultOp.right().value());
1084 lockComponent(containerComponent, "deleteComponentInstance");
1085 ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1087 deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
1088 containerComponentType, deletedCompInstance);
1089 ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1090 if (ActionStatus.OK != onDeleteOperationsStatus) {
1091 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1093 } catch (ComponentException e) {
1098 unlockComponent(failed, containerComponent);
1100 return deletedRelatedInst;
1103 public Either<ComponentInstance, ResponseFormat> deleteServiceFiltersRelatedTobeDeletedComponentInstance(
1104 Service service, ComponentInstance componentInstance, ComponentTypeEnum containerComponentType, String userId) {
1105 if (containerComponentType.equals(ComponentTypeEnum.SERVICE)) {
1106 Set<String> serviceFiltersIDsToBeDeleted =
1107 getServiceFiltersRelatedToComponentInstance(service.getUniqueId(), componentInstance);
1108 if (!serviceFiltersIDsToBeDeleted.isEmpty()) {
1109 Set<String> ids = service.getComponentInstances().stream()
1110 .filter(ci -> serviceFiltersIDsToBeDeleted
1111 .contains(ci.getName()))
1112 .map(ComponentInstance::getUniqueId)
1113 .collect(Collectors.toSet());
1114 Either<Set<String>, StorageOperationStatus> deleteServiceFiltersEither =
1115 serviceFilterOperation.deleteNodeFilters(service, ids);
1116 if (deleteServiceFiltersEither.isRight()) {
1117 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFiltersEither.right().value(),
1118 containerComponentType);
1119 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1121 for (String id : ids) {
1122 final Optional<ComponentInstance> componentInstanceById = service.getComponentInstanceById(id);
1123 if (!componentInstanceById.isPresent()){
1124 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1126 ComponentInstance ci = componentInstanceById.get();
1127 List<String> directives = ci.getDirectives();
1128 directives.remove(DirectivesUtils.SELECTABLE);
1129 ci.setDirectives(directives);
1130 final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither =
1131 updateComponentInstanceMetadata(ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUniqueId(),
1132 ci.getUniqueId(), userId, ci, true, false);
1133 if (componentInstanceResponseFormatEither.isRight()) {
1134 return componentInstanceResponseFormatEither;
1139 return Either.left(componentInstance);
1144 private Set<String> getServiceFiltersRelatedToComponentInstance(String containerComponentId,
1145 ComponentInstance componentInstance) {
1146 ComponentParametersView filter = new ComponentParametersView(true);
1147 filter.setIgnoreComponentInstances(false);
1148 Either<Service, StorageOperationStatus> serviceFilterOrigin =
1149 toscaOperationFacade.getToscaElement(containerComponentId, filter);
1150 final Service service = serviceFilterOrigin.left().value();
1151 final Set<String> nodesFiltersToBeDeleted = ServiceFilterUtils.getNodesFiltersToBeDeleted(service,
1153 return nodesFiltersToBeDeleted;
1157 ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId,
1158 ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1159 if(containerComponentType == ComponentTypeEnum.SERVICE){
1160 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
1161 if (!pathIDsToBeDeleted.isEmpty()) {
1162 deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
1165 return componentInstance;
1172 private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
1174 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1175 if(storageStatus.isRight()) {
1176 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
1178 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
1179 Sets.newHashSet(pathIdsToDelete));
1181 if(result.isRight()) {
1182 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
1186 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
1187 Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
1188 List<String> pathIDsToBeDeleted = new ArrayList<>();
1190 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
1191 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
1193 return pathIDsToBeDeleted;
1196 private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
1197 ComponentParametersView filter = new ComponentParametersView(true);
1198 filter.setIgnoreForwardingPath(false);
1199 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
1200 .getToscaElement(containerComponentId, filter);
1201 return forwardingPathOrigin.left().value().getForwardingPaths().values();
1204 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
1205 String componentInstanceId){
1206 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
1207 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
1208 elementDataDefinition.getToNode()
1209 .equalsIgnoreCase(componentInstanceId));
1213 private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
1214 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
1215 if (deleteRes.isRight()) {
1216 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
1217 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
1218 throw new ByActionStatusComponentException(status, componentInstanceId);
1220 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
1221 ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
1223 if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
1224 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1225 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
1226 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
1227 if (deleteInputsRes != StorageOperationStatus.OK) {
1228 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
1229 throw new ByActionStatusComponentException(
1230 componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId);
1234 return deletedInstance;
1237 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1238 ComponentInstance foundInstance = null;
1239 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1240 if (instance.getUniqueId().equals(componentInstanceId)) {
1241 foundInstance = instance;
1242 containerComponent.getComponentInstances().remove(instance);
1246 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1247 return foundInstance;
1250 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1251 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1252 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1256 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1257 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1260 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1261 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true);
1264 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock) {
1266 validateUserExists(userId);
1268 RequirementCapabilityRelDef requirementCapabilityRelDef = null;
1270 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1272 validateCanWorkOnComponent(containerComponent, userId);
1273 boolean failed = false;
1276 lockComponent(containerComponent, "associateRIToRI");
1278 requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
1279 }catch (ComponentException e){
1284 unlockComponent(failed, containerComponent);
1286 return requirementCapabilityRelDef;
1289 public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
1291 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1293 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
1295 if (result.isLeft()) {
1296 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1297 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1298 return requirementCapabilityRelDef;
1301 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1302 String fromNameOrId = "";
1303 String toNameOrId = "";
1304 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1305 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1307 toNameOrId = requirementDef.getFromNode();
1308 fromNameOrId = requirementDef.getFromNode();
1309 if (fromResult.isLeft()) {
1310 fromNameOrId = fromResult.left().value().getName();
1312 if (toResult.isLeft()) {
1313 toNameOrId = toResult.left().value().getName();
1316 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance
1317 (result.right().value(), true), fromNameOrId, toNameOrId,
1318 requirementDef.getRelationships().get(0).getRelation().getRequirement());
1324 * @param componentId
1326 * @param requirementDefList
1327 * @param componentTypeEnum
1330 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(
1333 List<RequirementCapabilityRelDef> requirementDefList,
1334 ComponentTypeEnum componentTypeEnum) {
1336 validateUserExists(userId);
1337 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1338 validateCanWorkOnComponent(containerComponent, userId);
1339 boolean failed = false;
1340 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1342 lockComponent(containerComponent, "associateRIToRI");
1343 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1344 RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(
1345 componentId, userId, requirementDef, containerComponent.getComponentType());
1346 delOkResult.add(requirementCapabilityRelDef);
1348 }catch (ComponentException e){
1352 unlockComponent(failed, containerComponent);
1358 public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1359 validateUserExists(userId);
1361 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1362 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1364 validateCanWorkOnComponent(containerComponent, userId);
1365 boolean failed = false;
1367 lockComponent(containerComponent, "associateRIToRI");
1368 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1369 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
1370 if (result.isLeft()) {
1371 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1372 return result.left().value();
1375 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1376 String fromNameOrId = "";
1377 String toNameOrId = "";
1378 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1379 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1381 toNameOrId = requirementDef.getFromNode();
1382 fromNameOrId = requirementDef.getFromNode();
1383 if (fromResult.isLeft()) {
1384 fromNameOrId = fromResult.left().value().getName();
1386 if (toResult.isLeft()) {
1387 toNameOrId = toResult.left().value().getName();
1390 throw new ByActionStatusComponentException(
1391 componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
1392 fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
1394 }catch (ComponentException e){
1398 unlockComponent(failed, containerComponent);
1402 * Allows to get relation contained in specified component according to received Id
1403 * @param componentId
1406 * @param componentTypeEnum
1409 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1411 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1413 org.openecomp.sdc.be.model.Component containerComponent = null;
1414 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1415 RequirementCapabilityRelDef foundRelation = null;
1417 validateUserExists(userId);
1418 containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1419 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1420 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1421 if(foundRelation == null){
1422 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1423 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1424 resultOp = Either.right(responseFormat);
1426 if(resultOp == null){
1427 resultOp = setRelatedCapability(foundRelation, containerComponent);
1429 if(resultOp.isLeft()){
1430 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1432 } catch (Exception e) {
1433 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1434 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1439 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1440 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1441 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1442 return relationship;
1448 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1449 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1450 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1451 String instanceId = foundRelation.getFromNode();
1452 Optional<RequirementDefinition> foundRequirement;
1453 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1454 if(!instance.isPresent()){
1455 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1456 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1457 result = Either.right(responseFormat);
1460 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1461 foundRequirement = requirements.stream().filter(r -> isBelongingCalcRequirement(relationshipInfo, r, containerComponent.getLifecycleState())).findFirst();
1462 if(foundRequirement.isPresent()){
1463 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1464 result = Either.left(foundRelation);
1469 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
1470 if(getfulfilledRequirementRes.isRight()){
1471 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1472 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1473 result = Either.right(responseFormat);
1475 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1479 result = Either.left(foundRelation);
1484 private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1485 return req.getName().equals(relationshipInfo.getRequirement()) &&
1486 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1487 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1490 private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
1491 return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) &&
1492 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1493 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1496 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1497 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1498 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1499 String instanceId = foundRelation.getToNode();
1500 Optional<CapabilityDefinition> foundCapability;
1501 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1502 if(!instance.isPresent()){
1503 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1504 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1505 result = Either.right(responseFormat);
1508 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1509 foundCapability = capabilities.stream().filter(c -> isBelongingCalcCapability(relationshipInfo, c, containerComponent.getLifecycleState())).findFirst();
1510 if(foundCapability.isPresent()){
1511 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1512 result = Either.left(foundRelation);
1517 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1518 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
1519 if(getfulfilledRequirementRes.isRight()){
1520 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1521 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1522 result = Either.right(responseFormat);
1524 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1528 result = Either.left(foundRelation);
1533 private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1534 return cap.getName().equals(relationshipInfo.getCapability()) &&
1535 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1536 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1539 private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
1540 return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) &&
1541 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1542 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1545 private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
1546 return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ?
1547 currName.equals(nameFromRelationship):
1548 previousName!= null && previousName.equals(nameFromRelationship);
1551 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1552 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1553 Either<ComponentInstanceProperty, ResponseFormat> result;
1554 if (eitherAttribute.isLeft()) {
1555 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1556 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1558 result = Either.left(instanceAttribute);
1561 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1563 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1565 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1571 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1573 Either<ComponentInstanceProperty, ResponseFormat> result;
1575 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1576 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1577 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1579 if (!errorWrapper.isEmpty()) {
1580 result = Either.right(errorWrapper.getInnerElement());
1582 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1583 if (eitherAttribute.isLeft()) {
1584 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1585 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1586 result = Either.left(instanceAttribute);
1589 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1591 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1592 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1600 * Create Or Updates Attribute Instance
1602 * @param componentTypeEnum
1603 * @param componentId
1604 * @param resourceInstanceId
1609 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1610 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1611 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1613 validateUserExists(userId);
1614 if (errorWrapper.isEmpty()) {
1615 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1617 if (errorWrapper.isEmpty()) {
1618 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1620 if (errorWrapper.isEmpty()) {
1621 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1625 if (errorWrapper.isEmpty()) {
1626 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1628 result = createAttributeValue(attribute, resourceInstanceId);
1630 result = updateAttributeValue(attribute, resourceInstanceId);
1633 result = Either.right(errorWrapper.getInnerElement());
1639 if (result == null || result.isRight()) {
1640 janusGraphDao.rollback();
1642 janusGraphDao.commit();
1645 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1649 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1651 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1653 /*-------------------------------Validations---------------------------------*/
1654 validateUserExists(userId);
1656 if (componentTypeEnum == null) {
1657 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1658 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1661 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1663 if (getResourceResult.isRight()) {
1664 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1665 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1666 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1668 Component containerComponent = getResourceResult.left().value();
1670 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1671 if (containerComponent.isArchived()) {
1672 log.info("Component is archived. Component id: {}", componentId);
1673 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1675 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1676 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1679 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1680 if (resourceInstanceStatus.isRight()) {
1681 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1682 resourceInstanceId, "resource instance", "service", componentId));
1684 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1687 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1688 if (lockStatus != StorageOperationStatus.OK) {
1689 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1690 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1692 List <ComponentInstanceProperty> updatedProperties = new ArrayList<>();
1694 for (ComponentInstanceProperty property: properties) {
1695 validateMandatoryFields(property);
1696 ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance);
1697 String propertyParentUniqueId = property.getParentUniqueId();
1698 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1699 if (updatedPropertyValue.isRight()) {
1700 log.error("Failed to update property object value of property: {}",
1702 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
1704 Optional<CapabilityDefinition>
1705 capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
1706 if(capPropDefinition.isPresent()) {
1707 updatedPropertyValue
1708 .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
1709 containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
1710 capPropDefinition.get().getName()), Either::right);
1713 updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property, updatedValue,
1714 containerComponent, foundResourceInstance), Either::right);
1715 updatedProperties.add(componentInstanceProperty);
1719 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1720 if (updateContainerRes.isRight()) {
1721 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1722 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1725 resultOp = Either.left(updatedProperties);
1729 if (resultOp == null || resultOp.isRight()) {
1730 janusGraphDao.rollback();
1732 janusGraphDao.commit();
1735 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1739 private void validateMandatoryFields(PropertyDataDefinition property) {
1740 if (StringUtils.isEmpty(property.getName())) {
1741 throw new ByActionStatusComponentException (ActionStatus.MISSING_PROPERTY_NAME);
1745 private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent, ComponentInstance foundResourceInstance) {
1746 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1747 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName())).findAny();
1748 if (!instanceProperty.isPresent()) {
1749 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
1751 return instanceProperty.get();
1756 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
1757 String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1758 String capabilityType, String capabilityName) {
1759 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1760 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
1761 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
1762 if (actionStatus != null) {
1763 return actionStatus;
1766 return componentsUtils.getResponseFormat(ActionStatus.OK);
1769 private ResponseFormat updateCapabilityPropFromUpdateInstProp(ComponentInstanceProperty property,
1770 String newValue, Component containerComponent,
1771 ComponentInstance foundResourceInstance,
1772 String capabilityType, String capabilityName) {
1773 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1774 Either<Component, StorageOperationStatus> getComponentRes =
1775 toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
1776 if(getComponentRes.isRight()) {
1777 return componentsUtils.getResponseFormat(getComponentRes.right().value());
1780 if(!PropertiesUtils.isNodeServiceProxy(getComponentRes.left().value())) {
1781 propOwner = componentInstanceUniqueId;
1783 propOwner = foundResourceInstance.getSourceModelUid();
1786 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
1787 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
1788 if (actionStatus != null) {
1789 return actionStatus;
1792 return componentsUtils.getResponseFormat(ActionStatus.OK);
1795 private ResponseFormat updateCapPropOnContainerComponent(ComponentInstanceProperty property, String newValue,
1796 Component containerComponent,
1797 ComponentInstance foundResourceInstance,
1798 String capabilityType, String capabilityName,
1799 String componentInstanceUniqueId) {
1800 Map<String, List<CapabilityDefinition>> capabilities =
1801 Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap());
1802 List<CapabilityDefinition> capPerType =
1803 Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST);
1804 Optional<CapabilityDefinition> cap =
1805 capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1806 if (cap.isPresent()) {
1807 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1808 if (capProperties != null) {
1809 Optional<ComponentInstanceProperty> instanceProperty =
1810 capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1811 StorageOperationStatus status;
1812 if (instanceProperty.isPresent()) {
1813 String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get());
1814 instanceProperty.get().setValue(newValue);
1815 List<String> path = new ArrayList<>();
1816 path.add(componentInstanceUniqueId);
1818 instanceProperty.get().setPath(path);
1819 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
1820 componentInstanceUniqueId, capKey, instanceProperty.get());
1821 if (status != StorageOperationStatus.OK) {
1822 ActionStatus actionStatus =
1823 componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1824 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1827 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1834 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1835 StorageOperationStatus status;
1836 instanceProperty.setValue(newValue);
1837 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
1838 if (status != StorageOperationStatus.OK) {
1839 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1840 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1842 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1843 return componentsUtils.getResponseFormat(ActionStatus.OK);
1846 private <T extends PropertyDefinition> Either<String,ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
1847 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1848 if (allDataTypesEither.isRight()) {
1849 JanusGraphOperationStatus status = allDataTypesEither.right().value();
1850 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1851 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1853 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1854 String propertyType = property.getType();
1855 String innerType = getInnerType(property);
1857 // Specific Update Logic
1858 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
1859 if (isValid.isRight()) {
1860 Boolean res = isValid.right().value();
1862 log.error("Invalid value {} of property {} ", newValue, property.getName());
1863 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1866 Object object = isValid.left().value();
1867 if (object != null) {
1868 newValue = object.toString();
1871 if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType))
1872 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
1873 return Either.left(newValue);
1876 private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes, String innerType, String propertyType) {
1878 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1879 if (pair.getRight() != null && !pair.getRight()) {
1880 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1887 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1888 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1889 if (allDataTypesEither.isRight()) {
1890 JanusGraphOperationStatus status = allDataTypesEither.right().value();
1891 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1892 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1894 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1895 String innerType = null;
1896 String propertyType = property.getType();
1897 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1898 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1900 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1901 SchemaDefinition def = property.getSchema();
1903 log.debug("Schema doesn't exists for property of type {}", type);
1904 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1906 PropertyDataDefinition propDef = def.getProperty();
1907 if (propDef == null) {
1908 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1909 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1911 innerType = propDef.getType();
1913 // Specific Update Logic
1914 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1915 String newValue = property.getValue();
1916 if (isValid.isRight()) {
1917 Boolean res = isValid.right().value();
1919 log.debug("validate and update property value has failed with value: {}", property.getValue());
1920 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
1923 Object object = isValid.left().value();
1924 if (object != null) {
1925 newValue = object.toString();
1929 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1930 if (pair.getRight() != null && pair.getRight() == false) {
1931 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1932 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
1935 return Either.left(newValue);
1938 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1939 StorageOperationStatus status;
1940 input.setValue(newValue);
1941 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1942 if (status != StorageOperationStatus.OK) {
1943 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1944 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1946 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1947 return componentsUtils.getResponseFormat(ActionStatus.OK);
1950 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1952 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1954 validateUserExists(userId);
1956 if (componentTypeEnum == null) {
1957 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1958 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1961 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1963 if (getResourceResult.isRight()) {
1964 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1965 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1966 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1968 Component containerComponent = getResourceResult.left().value();
1970 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1971 if (containerComponent.isArchived()) {
1972 log.info("Component is archived. Component id: {}", componentId);
1973 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1975 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1976 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1979 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1980 if (resourceInstanceStatus.isRight()) {
1981 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1982 resourceInstanceId, "resource instance", "service", componentId));
1985 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1988 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1989 if (lockStatus != StorageOperationStatus.OK) {
1990 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1991 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1993 List <ComponentInstanceInput> updatedInputs = new ArrayList<>();
1995 for (ComponentInstanceInput input: inputs) {
1996 validateMandatoryFields(input);
1997 ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
1998 Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
1999 if (validatedInputValue.isRight()){
2000 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
2002 updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent, foundResourceInstance);
2003 updatedInputs.add(componentInstanceInput);
2005 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2006 if (updateContainerRes.isRight()) {
2007 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2008 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2011 resultOp = Either.left(updatedInputs);
2015 if (resultOp == null || resultOp.isRight()) {
2016 janusGraphDao.rollback();
2018 janusGraphDao.commit();
2021 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2026 private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent, ComponentInstance foundResourceInstance) {
2027 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
2028 Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
2029 if (!instanceInput.isPresent()) {
2030 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName());
2032 return instanceInput.get();
2035 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, String userId) {
2037 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2039 validateUserExists(userId);
2041 if (componentTypeEnum == null) {
2042 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2043 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2047 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2048 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2049 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2053 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2054 if (lockStatus != StorageOperationStatus.OK) {
2055 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2056 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2060 String propertyValueUid = property.getValueUniqueUid();
2062 if (propertyValueUid == null) {
2064 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
2066 if (counterRes.isRight()) {
2067 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
2068 StorageOperationStatus status = counterRes.right().value();
2069 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2070 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2072 Integer index = counterRes.left().value();
2073 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
2075 if (result.isLeft()) {
2076 log.trace("Property value was added to resource instance {}", resourceInstanceId);
2077 ComponentInstanceProperty instanceProperty = result.left().value();
2079 resultOp = Either.left(instanceProperty);
2082 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
2084 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2086 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2090 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
2092 if (result.isLeft()) {
2093 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
2094 ComponentInstanceProperty instanceProperty = result.left().value();
2096 resultOp = Either.left(instanceProperty);
2099 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
2101 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2103 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2106 if (resultOp.isLeft()) {
2107 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
2108 if (updateCustomizationUUID != StorageOperationStatus.OK) {
2109 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
2111 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2118 if (resultOp == null || resultOp.isRight()) {
2119 janusGraphDao.rollback();
2121 janusGraphDao.commit();
2124 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2129 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
2131 validateUserExists(userId);
2133 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2135 if (componentTypeEnum == null) {
2136 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2137 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2141 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2142 log.info("Restricted operation for user {} on service {}", userId, serviceId);
2143 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2147 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2148 if (lockStatus != StorageOperationStatus.OK) {
2149 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2150 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2154 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2156 if (result.isLeft()) {
2157 log.debug("Property value {} was removed from graph.", propertyValueId);
2158 ComponentInstanceProperty instanceProperty = result.left().value();
2160 resultOp = Either.left(instanceProperty);
2164 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2166 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2168 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2174 if (resultOp == null || resultOp.isRight()) {
2175 janusGraphDao.rollback();
2177 janusGraphDao.commit();
2180 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2185 private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) {
2187 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType());
2188 Component component;
2189 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2190 if (getComponentRes.isRight()) {
2191 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
2192 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2193 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2195 component = getComponentRes.left().value();
2196 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2197 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2198 ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
2199 throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
2201 if (component.isArchived() == true){
2202 ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
2203 throw new ByActionStatusComponentException(actionStatus, component.getName());
2208 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2209 String containerComponentId,
2210 String componentInstanceId,
2211 ComponentInstance newComponentInstance) {
2212 Either<Set<String>, ResponseFormat> resultOp;
2213 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2214 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2217 Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2219 //Fetch current component instance
2220 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2221 getResourceInstanceById(containerComponent, componentInstanceId);
2222 if (eitherResourceInstance.isRight()) {
2223 resultOp = Either.right(componentsUtils.getResponseFormat(
2224 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2227 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2229 //Check whether new componentInstance exists
2230 String resourceId = newComponentInstance.getComponentUid();
2231 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2232 if (componentExistsRes.isRight()) {
2233 log.debug("Failed to find resource {}", resourceId);
2234 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2235 (componentExistsRes.right().value()), resourceId));
2237 } else if (!componentExistsRes.left().value()) {
2238 log.debug("The resource {} not found ", resourceId);
2239 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2243 //Fetch component using new component instance uid
2244 Component updatedContainerComponent=getOriginComponentFromComponentInstance(newComponentInstance);
2245 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2246 currentResourceInstance, updatedContainerComponent);
2247 resultOp=Either.left(toDeleteForwardingPaths);
2252 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2253 Component updatedContainerComponent) {
2254 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2255 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
2257 Service service = (Service) containerComponent;
2258 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2260 return forwardingPathUtils.
2261 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2264 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2265 ComponentParametersView componentParametersView = new ComponentParametersView();
2266 componentParametersView.setIgnoreCapabiltyProperties(false);
2267 componentParametersView.setIgnoreForwardingPath(false);
2268 return componentParametersView;
2271 public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2273 User user = validateUserExists(userId);
2274 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2275 ComponentParametersView componentParametersView = new ComponentParametersView();
2276 componentParametersView.setIgnoreCapabiltyProperties(false);
2278 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2280 validateCanWorkOnComponent(containerComponent, userId);
2282 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2283 if (resourceInstanceStatus.isRight()) {
2284 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId);
2287 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2289 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
2292 public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance,
2293 ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType ) {
2294 boolean failed = false;
2295 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2298 lockComponent(containerComponent, "changeComponentInstanceVersion");
2299 String containerComponentId = containerComponent.getUniqueId();
2300 String componentInstanceId = currentResourceInstance.getUniqueId();
2301 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2302 return currentResourceInstance;
2304 String resourceId = newComponentInstance.getComponentUid();
2306 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2307 if (componentExistsRes.isRight()) {
2308 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, componentExistsRes.right().value());
2309 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId);
2310 } else if (!componentExistsRes.left().value()) {
2311 log.debug("The resource {} not found ", resourceId);
2312 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2315 Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2317 DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent);
2318 ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
2319 Component origComponent = null;
2320 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2321 if (originType == OriginTypeEnum.ServiceProxy) {
2322 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
2323 if (isServiceProxyOrigin(serviceProxyOrigin))
2324 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
2325 origComponent = serviceProxyOrigin.left().value();
2327 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2329 if (isFillProxyRes(fillProxyRes))
2330 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
2331 newComponentInstance.setOriginType(originType);
2333 origComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2334 newComponentInstance.setName(resResourceInfo.getName());
2337 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2338 newComponentInstance.setPosX(resResourceInfo.getPosX());
2339 newComponentInstance.setPosY(resResourceInfo.getPosY());
2340 newComponentInstance.setDescription(resResourceInfo.getDescription());
2342 ComponentInstance updatedComponentInstance = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2343 dataHolder.setCurrInstanceNode(origComponent);
2344 Component mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2346 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2347 if (postChangeVersionResult != ActionStatus.OK) {
2348 throw new ByActionStatusComponentException(postChangeVersionResult);
2351 ComponentParametersView filter = new ComponentParametersView(true);
2352 filter.setIgnoreComponentInstances(false);
2353 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2354 if (updatedComponentRes.isRight()) {
2355 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2356 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2357 log.debug("Component with id {} was not found", containerComponentId);
2358 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2360 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2361 if (resourceInstanceStatus.isRight()) {
2362 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
2363 (resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId());
2365 return resourceInstanceStatus.left().value();
2367 }catch (ComponentException e){
2371 unlockComponent(failed, containerComponent);
2375 private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) {
2376 if (fillProxyRes != StorageOperationStatus.OK) {
2377 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2384 public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2385 Component containerComponent = null;
2387 boolean failed = false;
2389 validateUserExists(userId);
2390 validateComponentType(containerComponentTypeParam);
2392 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2393 if (validateContainerComponentExists.isRight()) {
2394 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
2396 containerComponent = validateContainerComponentExists.left().value();
2398 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2399 if (resourceInstanceStatus.isRight()) {
2400 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
2403 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2404 if (CollectionUtils.isEmpty(instanceProperties)) {
2405 instanceProperties = new ArrayList<>();
2407 return instanceProperties;
2408 }catch (ComponentException e){
2412 unlockComponent(failed, containerComponent);
2416 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2417 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2419 if (counterRes.isRight()) {
2420 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2421 StorageOperationStatus status = counterRes.right().value();
2422 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2423 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2425 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2431 * updates componentInstance modificationTime
2433 * @param componentInstance
2434 * @param componentInstanceType
2435 * @param modificationTime
2436 * @param inTransaction
2439 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2440 Either<ComponentInstanceData, ResponseFormat> result;
2441 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2443 if (updateComponentInstanceRes.isRight()) {
2444 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2445 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2447 result = Either.left(updateComponentInstanceRes.left().value());
2452 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2453 // TODO Add implementation
2454 return Either.left(new ComponentInstance());
2457 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2458 // TODO Add implementation
2459 return Either.left(new ComponentInstance());
2462 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2463 // TODO Add implementation
2464 return Either.left(new ComponentInstance());
2467 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2468 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2471 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2473 Either<ComponentInstance, StorageOperationStatus> result = null;
2474 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2475 Optional<ComponentInstance> foundInstance = null;
2476 if (CollectionUtils.isEmpty(instances)) {
2477 result = Either.right(StorageOperationStatus.NOT_FOUND);
2479 if (result == null) {
2480 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2481 if (!foundInstance.isPresent()) {
2482 result = Either.right(StorageOperationStatus.NOT_FOUND);
2485 if (result == null) {
2486 result = Either.left(foundInstance.get());
2491 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2493 Long creationDate = origInstanceForUpdate.getCreationTime();
2495 Long modificationTime = System.currentTimeMillis();
2496 resourceInstanceForUpdate.setCreationTime(creationDate);
2497 resourceInstanceForUpdate.setModificationTime(modificationTime);
2499 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2501 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2502 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2505 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2507 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2508 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2510 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2511 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2513 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2514 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2516 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2517 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2519 if (resourceInstanceForUpdate.getOriginType() == null) {
2520 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2522 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2523 resourceInstanceForUpdate.setIsProxy(true);
2524 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2525 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2527 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2528 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2530 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2531 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2533 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2534 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2536 if (resourceInstanceForUpdate.getCreatedFrom() == null) {
2537 resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom());
2539 return resourceInstanceForUpdate;
2542 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2543 * @param containerComponentType
2544 * @param containerComponentId
2545 * @param componentInstanceUniqueId
2546 * @param capabilityType
2547 * @param capabilityName
2552 public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2554 Component containerComponent = null;
2556 List<ComponentInstanceProperty> resultOp = null;
2558 validateUserExists(userId);
2559 validateComponentType(containerComponentType);
2560 containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException);
2561 ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left().on(this::componentInstanceException);
2562 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.getCapabilities());
2563 } catch(StorageException e){
2564 unlockRollbackWithException(containerComponent, e);
2565 } catch (ComponentException e) {
2566 unlockRollbackWithException(containerComponent, e);
2567 } catch (Exception e){
2568 unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
2570 unlockWithCommit(containerComponent);
2574 private List<ComponentInstanceProperty> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2575 CapabilityDefinition foundCapability;
2576 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2577 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2578 if (capabilitiesPerType != null) {
2579 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2580 if (capabilityOpt.isPresent()) {
2581 foundCapability = capabilityOpt.get();
2582 return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
2586 return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2589 private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2591 return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
2593 .on(this::componentInstancePropertyListException);
2594 } catch(Exception e){
2595 log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2596 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
2600 /*private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2601 String capabilityType, String capabilityName, String ownerId) {
2602 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2603 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2604 .orElse(Collections.emptyMap());
2605 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2606 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2607 if (cap.isPresent()) {
2608 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2609 if (capProperties != null) {
2610 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2611 StorageOperationStatus status;
2612 if (instanceProperty.isPresent()) {
2613 String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get());
2614 instanceProperty.get().setValue(newValue);
2615 List<String> path = new ArrayList<>();
2616 path.add(componentInstanceUniqueId);
2618 instanceProperty.get().setPath(path);
2619 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2620 if (status != StorageOperationStatus.OK) {
2621 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2622 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2625 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2629 return componentsUtils.getResponseFormat(ActionStatus.OK);
2632 /*public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2633 List<ComponentInstanceProperty> properties, String userId) {
2634 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2636 validateUserExists(userId);
2638 if (componentTypeEnum == null) {
2639 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2640 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2642 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2644 if (getResourceResult.isRight()) {
2645 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2646 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2648 Component containerComponent = getResourceResult.left().value();
2650 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2651 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2652 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2654 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2655 if (resourceInstanceStatus.isRight()) {
2656 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2658 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2660 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2661 if (lockStatus != StorageOperationStatus.OK) {
2662 log.debug("Failed to lock component {}", containerComponentId);
2663 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2666 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
2667 if (allDataTypes.isRight()) {
2668 JanusGraphOperationStatus status = allDataTypes.right().value();
2669 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2670 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
2674 for (ComponentInstanceProperty property : properties) {
2675 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, false);
2676 newPropertyValueEither.bimap(updatedValue ->
2677 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2680 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2682 if (updateContainerRes.isRight()) {
2683 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2684 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2687 resultOp = Either.left(properties);
2691 if (resultOp == null || resultOp.isRight()) {
2692 janusGraphDao.rollback();
2694 janusGraphDao.commit();
2697 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2701 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2702 List<ComponentInstanceProperty> properties, String userId) {
2703 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2705 validateUserExists(userId);
2706 if (componentTypeEnum == null) {
2707 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2708 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2710 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2712 if (getResourceResult.isRight()) {
2713 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2714 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2716 Component containerComponent = getResourceResult.left().value();
2718 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2719 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2720 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2722 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2723 if (resourceInstanceStatus.isRight()) {
2724 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2726 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2728 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2729 if (lockStatus != StorageOperationStatus.OK) {
2730 log.debug("Failed to lock component {}", containerComponentId);
2731 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2735 for (ComponentInstanceProperty property : properties) {
2736 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
2737 newPropertyValueEither.bimap(updatedValue ->
2738 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2741 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2743 if (updateContainerRes.isRight()) {
2744 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2745 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2748 resultOp = Either.left(properties);
2752 if (resultOp == null || resultOp.isRight()) {
2753 janusGraphDao.rollback();
2755 janusGraphDao.commit();
2758 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2762 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
2763 String containerComponentId,
2764 String componentInstanceId,
2767 Map<String, ComponentInstance> resultMap = new HashMap<>();
2768 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2769 if (getOrigComponent.isRight()) {
2770 log.error("Failed to get the original component information");
2771 return Either.right(componentsUtils.getResponseFormat(
2772 ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2775 Component origComponent = getOrigComponent.left().value();
2778 lockComponent(origComponent, "copyComponentInstance");
2780 } catch (ComponentException e) {
2781 log.error("destComponentInstance's data is {}", origComponent.toString());
2782 return Either.right(componentsUtils.getResponseFormat(
2783 ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}", origComponent.toString()));
2786 boolean failed = false;
2787 ComponentInstance actionResponse = null;
2790 actionResponse = createComponentInstance(
2791 "services", containerComponentId, userId, inputComponentInstance, true, false);
2793 } catch (ComponentException e) {
2798 // on failure of the create instance unlock the resource and rollback the transaction.
2799 if (null == actionResponse || failed) {
2800 janusGraphDao.rollback();
2801 log.error("Failed to copy the component instance to the canvas");
2803 unlockComponent(failed, origComponent);
2805 return Either.right(componentsUtils.getResponseFormat(
2806 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2810 Either<String, ResponseFormat> resultOp = null;
2813 ComponentInstance destComponentInstance = actionResponse;
2814 log.debug("destComponentInstance's data is {}", destComponentInstance.toString());
2817 resultOp = deepCopyComponentInstance(
2818 origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
2820 resultMap.put("componentInstance", destComponentInstance);
2824 if (resultOp == null || resultOp.isRight()) {
2825 unlockComponent(true, origComponent);
2826 janusGraphDao.rollback();
2827 log.error("Failed to deep copy component instance");
2828 return Either.right(componentsUtils.getResponseFormat(
2829 ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
2831 unlockComponent(false, origComponent);
2832 janusGraphDao.commit();
2833 log.debug("Success trasaction commit");
2837 return Either.left(resultMap);
2840 private Either<String, ResponseFormat> deepCopyComponentInstance(
2841 Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
2842 ComponentInstance destComponentInstance, String userId) {
2844 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2845 if (getDestComponent.isRight()) {
2846 log.error("Failed to get the dest component information");
2847 return Either.right(componentsUtils.getResponseFormat(
2848 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2851 Component destComponent = getDestComponent.left().value();
2853 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
2854 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2855 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
2856 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
2857 return Either.right(componentsUtils.getResponseFormat(
2858 ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
2861 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
2862 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2863 if (copyComponentInstanceWithAttributes.isRight()) {
2864 log.error("Failed to copy component instance with attributes as part of deep copy");
2865 return Either.right(componentsUtils.getResponseFormat(
2866 ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
2868 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2871 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
2872 Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
2873 ComponentInstance destComponentInstance, String userId) {
2874 log.debug("start to copy ComponentInstance with properties and inputs");
2876 List<ComponentInstanceProperty> sourcePropList = null;
2877 if (sourceComponent.getComponentInstancesProperties() != null
2878 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
2879 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
2880 log.debug("sourcePropList");
2883 List<ComponentInstanceProperty> destPropList = null;
2884 String destComponentInstanceId = destComponentInstance.getUniqueId();
2885 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
2886 if (destComponent.getComponentInstancesProperties() != null
2887 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
2888 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
2889 log.debug("destPropList {}");
2892 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
2894 if (null != destPropList && null != sourcePropList) {
2895 log.debug("start to set property and attribute");
2896 for (ComponentInstanceProperty destProp : destPropList) {
2897 String destPropertyName = destProp.getName();
2898 for (ComponentInstanceProperty sourceProp : sourcePropList) {
2899 if (!destPropertyName.equals(sourceProp.getName())) {
2902 log.debug("now set property");
2903 if (sourceProp.getGetInputValues() == null && !StringUtils.isEmpty(sourceProp.getValue())
2904 && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
2905 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
2907 destProp.setValue(sourceProp.getValue());
2908 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
2909 destComponent.getUniqueId(), destComponentInstanceId, destProp);
2910 if (updatePropertyValueEither.isRight()) {
2911 log.error("Failed to copy the property {}", destPropertyName);
2912 return Either.right(componentsUtils.getResponseFormat(
2913 ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
2918 log.debug("Now start to update inputs");
2920 if (sourceProp.getGetInputValues() != null) {
2921 if (sourceProp.getGetInputValues().size() < 1) {
2922 log.debug("property is return from input, set by man");
2925 log.debug("Now starting to copy the {} property", destPropertyName);
2927 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
2928 sourceComponent, sourceProp.getGetInputValues().get(0).getInputId());
2929 if (getSourceInputDefaultValue.isRight()) {
2930 return Either.right(getSourceInputDefaultValue.right().value());
2932 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
2937 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2940 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
2941 Component destComponent,
2942 String sourceComponentInstanceId,
2943 ComponentInstance destComponentInstance,
2945 String destComponentInstanceId = destComponentInstance.getUniqueId();
2947 log.info("start to copy component instance with attributes");
2949 List<ComponentInstanceProperty> sourceAttributeList = null;
2950 if (sourceComponent.getComponentInstancesAttributes() != null
2951 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
2952 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
2953 log.info("sourceAttributes {}");
2956 List<ComponentInstanceProperty> destAttributeList = null;
2957 if (destComponent.getComponentInstancesAttributes() != null
2958 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
2959 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
2960 log.info("destAttributeList {}");
2962 if (null != sourceAttributeList && null != destAttributeList) {
2963 log.info("set attribute");
2965 for (ComponentInstanceProperty sourceAttribute : sourceAttributeList) {
2966 String sourceAttributeName = sourceAttribute.getName();
2967 for (ComponentInstanceProperty destAttribute : destAttributeList) {
2968 if (sourceAttributeName.equals(destAttribute.getName())) {
2969 if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) {
2970 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
2972 sourceAttribute.setUniqueId(
2973 UniqueIdBuilder.buildResourceInstanceUniuqeId(
2974 "attribute" , destComponentInstanceId.split("\\.")[1] , sourceAttributeName));
2976 Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValueEither =
2977 createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
2978 destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
2980 if (updateAttributeValueEither.isRight()) {
2981 log.error("Failed to copy the attribute");
2982 return Either.right(componentsUtils
2983 .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
2984 "Failed to paste component instance to the canvas, attribute copy"));
2993 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2996 private Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
2998 String resourceInstanceId,
2999 ComponentInstanceProperty attribute,
3002 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
3004 validateUserExists(userId);
3006 if (componentTypeEnum == null) {
3007 BeEcompErrorManager.getInstance().logInvalidInputError(
3008 "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3009 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3013 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
3015 if (getResourceResult.isRight()) {
3016 log.info("Failed to retrieve component id {}", componentId);
3017 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3021 Component containerComponent = getResourceResult.left().value();
3023 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
3025 if (resourceInstanceStatus.isRight()) {
3026 resultOp = Either.right(componentsUtils.getResponseFormat(
3027 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
3031 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3034 String propertyType = attribute.getType();
3035 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
3036 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
3038 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
3039 SchemaDefinition def = attribute.getSchema();
3041 log.info("Schema doesn't exists for attribute of type {}", type);
3042 return Either.right(componentsUtils.getResponseFormat(
3043 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3045 PropertyDataDefinition propDef = def.getProperty();
3046 if (propDef == null) {
3047 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
3048 return Either.right(componentsUtils.getResponseFormat(
3049 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3053 List<ComponentInstanceProperty> instanceAttributes = containerComponent.
3054 getComponentInstancesAttributes().get(resourceInstanceId);
3055 Optional<ComponentInstanceProperty> instanceAttribute =
3056 instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
3057 StorageOperationStatus status;
3059 if (instanceAttribute.isPresent()) {
3060 log.info("updateComponentInstanceAttribute");
3061 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3063 log.info("addComponentInstanceAttribute");
3064 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3066 if (status != StorageOperationStatus.OK) {
3067 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3068 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3071 List<String> path = new ArrayList<>();
3072 path.add(foundResourceInstance.getUniqueId());
3073 attribute.setPath(path);
3075 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3076 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3077 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3079 if (updateContainerRes.isRight()) {
3080 ActionStatus actionStatus = componentsUtils.
3081 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3082 resultOp = Either.right(componentsUtils.
3083 getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3086 resultOp = Either.left(attribute);
3093 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
3094 String componentInstanceId,
3095 ComponentInstanceProperty property) {
3096 Either<String, ResponseFormat> resultOp;
3097 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3099 if (getComponent.isRight()) {
3100 log.error("Failed to get the component information");
3101 return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
3102 ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3105 Component containerComponent = getComponent.left().value();
3107 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
3108 containerComponent, componentInstanceId, property);
3109 if (status != StorageOperationStatus.OK) {
3110 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3111 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3115 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3116 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3118 if (updateContainerRes.isRight()) {
3119 ActionStatus actionStatus = componentsUtils.
3120 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3121 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3125 return Either.left("Update OK");
3128 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3129 List<InputDefinition> inputList = component.getInputs();
3130 for (InputDefinition input : inputList) {
3131 if (input.getUniqueId().equals(inputId)) {
3132 if (input.getDefaultValue() == null) {
3133 log.debug("The input's default value is null");
3134 return Either.left(null);
3136 return Either.left(input.getDefaultValue());
3139 log.error("The input's default value with id {} is not found", inputId);
3140 return Either.right(componentsUtils.getResponseFormat(
3141 ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3145 * Method to delete selected nodes and edges on composition page
3146 * @param containerComponentType
3147 * @param componentId
3148 * @param componentInstanceIdList
3152 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
3154 List<String> componentInstanceIdList,
3157 List<String> deleteErrorIds = new ArrayList<>();
3158 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3159 validateUserExists(userId);
3160 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, ComponentTypeEnum.findByParamName(containerComponentType), null);
3162 boolean failed = false;
3164 lockComponent(containerComponent, "batchDeleteComponentInstance");
3165 for (String eachInstanceId : componentInstanceIdList) {
3166 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
3167 containerComponent, containerComponentType, componentId, eachInstanceId);
3168 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3169 if (actionResponse.isRight()) {
3170 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3171 deleteErrorIds.add(eachInstanceId);
3174 //sending the ids of the error nodes that were not deleted to UI
3175 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3176 return deleteErrorMap;
3177 }catch (ComponentException e){
3181 unlockComponent(failed, containerComponent);
3185 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
3186 String containerComponentType,
3187 String containerComponentId,
3188 String componentInstanceId) {
3190 ComponentInstance resultOp;
3191 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3193 boolean failed = false;
3195 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3196 log.info("Successfully deleted instance with id {}", componentInstanceId);
3197 return Either.left(resultOp);
3199 catch (ComponentException e){
3200 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3201 return Either.right(new ResponseFormat());