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 java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.Objects;
30 import java.util.Optional;
31 import java.util.UUID;
32 import java.util.stream.Collectors;
34 import org.apache.commons.collections.CollectionUtils;
35 import org.apache.commons.collections.MapUtils;
36 import org.apache.commons.lang.StringUtils;
37 import org.apache.commons.lang3.tuple.ImmutablePair;
38 import org.openecomp.sdc.be.config.BeEcompErrorManager;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
40 import org.openecomp.sdc.be.dao.api.ActionStatus;
41 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
42 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
43 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
44 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
48 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
49 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
51 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
52 import org.openecomp.sdc.be.model.ArtifactDefinition;
53 import org.openecomp.sdc.be.model.Component;
54 import org.openecomp.sdc.be.model.ComponentInstance;
55 import org.openecomp.sdc.be.model.ComponentInstanceInput;
56 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
57 import org.openecomp.sdc.be.model.ComponentParametersView;
58 import org.openecomp.sdc.be.model.DataTypeDefinition;
59 import org.openecomp.sdc.be.model.GroupDefinition;
60 import org.openecomp.sdc.be.model.GroupInstance;
61 import org.openecomp.sdc.be.model.InputDefinition;
62 import org.openecomp.sdc.be.model.LifecycleStateEnum;
63 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
64 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
65 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
66 import org.openecomp.sdc.be.model.Resource;
67 import org.openecomp.sdc.be.model.User;
68 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
69 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
70 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
71 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
72 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
73 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
74 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
75 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
76 import org.openecomp.sdc.be.resources.data.PropertyValueData;
77 import org.openecomp.sdc.be.tosca.ToscaUtils;
78 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
79 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
80 import org.openecomp.sdc.common.api.Constants;
81 import org.openecomp.sdc.common.datastructure.Wrapper;
82 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
83 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
84 import org.openecomp.sdc.common.util.ValidationUtils;
85 import org.openecomp.sdc.exception.ResponseFormat;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88 import org.springframework.beans.factory.annotation.Autowired;
90 import fj.data.Either;
92 public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
94 private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName());
97 private IComponentInstanceOperation componentInstanceOperation;
100 private ArtifactsBusinessLogic artifactBusinessLogic;
102 private ApplicationDataTypeCache dataTypeCache;
104 public static final String VF_MODULE = "org.openecomp.groups.VfModule";
106 public ComponentInstanceBusinessLogic() {
109 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
110 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
113 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
115 Component origComponent = null;
116 Either<ComponentInstance, ResponseFormat> resultOp = null;
118 org.openecomp.sdc.be.model.Component containerComponent = null;
119 ComponentTypeEnum containerComponentType;
122 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
123 if (resp.isRight()) {
124 return Either.right(resp.right().value());
126 user = resp.left().value();
129 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
130 if (validateValidJson.isRight()) {
131 return Either.right(validateValidJson.right().value());
134 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
135 if (validateComponentType.isRight()) {
136 return Either.right(validateComponentType.right().value());
138 containerComponentType = validateComponentType.left().value();
141 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
142 if (validateComponentExists.isRight()) {
143 return Either.right(validateComponentExists.right().value());
145 containerComponent = validateComponentExists.left().value();
148 if (ToscaUtils.isAtomicType(containerComponent)) {
149 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
150 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
153 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
154 if (validateCanWorkOnComponent.isRight()) {
155 return Either.right(validateCanWorkOnComponent.right().value());
158 if (resourceInstance != null && containerComponentType != null) {
159 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
160 if (getOriginComponentRes.isRight()) {
161 return Either.right(getOriginComponentRes.right().value());
163 origComponent = getOriginComponentRes.left().value();
167 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
168 if (lockComponent.isRight()) {
169 return Either.right(lockComponent.right().value());
172 log.debug("Try to create entry on graph");
173 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
178 unlockComponent(resultOp, containerComponent);
182 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
184 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
185 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
186 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
188 Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false);
189 if (resp.isRight()) {
190 return Either.right(resp.right().value());
193 User user = resp.left().value();
194 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
195 if (validateComponentType.isRight()) {
196 return Either.right(validateComponentType.right().value());
199 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
201 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
202 if (validateComponentExists.isRight()) {
203 return Either.right(validateComponentExists.right().value());
205 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
207 if (ToscaUtils.isAtomicType(containerComponent)) {
208 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
209 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
212 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
213 if (validateCanWorkOnComponent.isRight()) {
214 return Either.right(validateCanWorkOnComponent.right().value());
217 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
218 if (lockComponent.isRight()) {
219 return Either.right(lockComponent.right().value());
223 log.debug("Try to create entry on graph");
224 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, true);
226 if (eitherResourceName.isRight()) {
227 resultOp = Either.right(eitherResourceName.right().value());
230 Component origComponent = eitherResourceName.left().value();
232 Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
233 if (result.isRight()) {
234 log.debug("Failed to create resource instance {}", containerComponentId);
235 resultOp = Either.right(result.right().value());
240 log.debug("Entity on graph is created.");
241 ComponentInstance resResourceInfo = result.left().value();
242 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
243 associationInfo.setFromNode(resResourceInfo.getUniqueId());
245 associationInfo.setToNode(resResourceInfo.getUniqueId());
248 RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo);
249 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
250 if (resultReqCapDef.isLeft()) {
251 log.debug("Enty on graph is created.");
252 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
253 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
254 resultOp = Either.left(resInfo);
258 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
259 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
264 unlockComponent(resultOp, containerComponent);
268 private Either<Component, ResponseFormat> getOriginComponentNameFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) {
269 Either<Component, ResponseFormat> eitherResponse;
270 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
271 if (eitherComponent.isRight()) {
272 log.debug("Failed to get origin component with id {} for component instance {} ", componentInstance.getComponentUid(), componentInstance.getName());
273 eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
275 eitherResponse = Either.left(eitherComponent.left().value());
277 return eitherResponse;
280 private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
281 Either<ComponentInstance, ResponseFormat> resultOp;
283 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
285 if (result.isRight()) {
286 log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
287 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
291 log.debug("Entity on graph is created.");
292 Component updatedComponent = result.left().value().getLeft();
293 Map<String, String> existingEnvVersions = new HashMap<>();
294 //TODO existingEnvVersions ??
295 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
296 if (addComponentInstanceArtifacts.isRight()) {
297 log.debug("Failed to create component instance {}", componentInstance.getName());
298 resultOp = Either.right(addComponentInstanceArtifacts.right().value());
302 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
303 if (!updatedInstanceOptional.isPresent()) {
304 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
305 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
308 resultOp = Either.left(updatedInstanceOptional.get());
313 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
315 * @param componentInstance
317 * @param existingEnvVersions
319 * @param containerComponentId
323 protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user,
324 Map<String, String> existingEnvVersions) {
325 log.debug("add artifacts to resource instance");
326 List<GroupDefinition> filteredGroups = null;
327 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
328 if (!ActionStatus.OK.equals(status)) {
329 ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
330 return Either.right(resultOp);
333 // generate heat_env if necessary
334 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
335 if (componentDeploymentArtifacts == null) {
336 return Either.left(ActionStatus.OK);
338 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
340 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
342 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
343 String type = artifact.getArtifactType();
345 if ( !type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) ){
346 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
349 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
353 if (artifact.checkEsIdExist()) {
354 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
355 componentInstance.getName(), user, containerComponent, existingEnvVersions);
356 if (createHeatEnvPlaceHolder.isRight()) {
357 return Either.right(createHeatEnvPlaceHolder.right().value());
359 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
362 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
364 if(CollectionUtils.isNotEmpty(originComponent.getGroups())){
365 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
367 if (CollectionUtils.isNotEmpty(filteredGroups)) {
368 for (GroupDefinition groupInstance : filteredGroups) {
369 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
370 if (op.isPresent()) {
371 List<ArtifactDefinition> artifactsUid;
372 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
373 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
375 artifactsUid = new ArrayList<>();
377 artifactsUid.add(artifactDefinition);
378 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
386 StorageOperationStatus artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
387 if ( artStatus != StorageOperationStatus.OK){
388 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
389 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
392 StorageOperationStatus result = toscaOperationFacade
393 .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
394 if (result != StorageOperationStatus.OK) {
395 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
396 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
398 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
399 return Either.left(ActionStatus.OK);
402 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
403 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null);
405 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
406 if (getResourceDeploymentArtifacts.isRight()) {
407 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
408 if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
409 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
410 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
413 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
416 if (!deploymentArtifacts.isEmpty()) {
417 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
418 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
419 if (!artifact.getValue().checkEsIdExist()) {
420 tempDeploymentArtifacts.remove(artifact.getKey());
424 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
427 return ActionStatus.OK;
430 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
431 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
434 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
435 boolean needLock, boolean createNewTransaction) {
437 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
438 if (resp.isRight()) {
439 return Either.right(resp.right().value());
442 Either<ComponentInstance, ResponseFormat> resultOp = null;
444 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
445 if (validateComponentType.isRight()) {
446 return Either.right(validateComponentType.right().value());
449 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
451 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
452 if (validateComponentExists.isRight()) {
453 return Either.right(validateComponentExists.right().value());
455 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
457 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
458 if (validateCanWorkOnComponent.isRight()) {
459 return Either.right(validateCanWorkOnComponent.right().value());
461 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
462 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
463 if (validateParentStatus.isRight()) {
464 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
465 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
468 if (!validateParentStatus.left().value()) {
469 resultOp = Either.right(
470 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
475 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
476 if (lockComponent.isRight()) {
477 return Either.right(lockComponent.right().value());
482 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
484 if (eitherResourceName.isRight()) {
485 resultOp = Either.right(eitherResourceName.right().value());
488 Component origComponent = eitherResourceName.left().value();
490 resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction);
495 unlockComponent(resultOp, containerComponent);
499 // New Multiple Instance Update API
500 public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock,
501 boolean createNewTransaction) {
503 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
504 org.openecomp.sdc.be.model.Component containerComponent = null;
506 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true);
507 if (resp.isRight()) {
508 return Either.right(resp.right().value());
511 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
512 if (validateComponentType.isRight()) {
513 return Either.right(validateComponentType.right().value());
516 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
518 ComponentParametersView componentFilter = new ComponentParametersView();
519 componentFilter.disableAll();
520 componentFilter.setIgnoreUsers(false);
521 componentFilter.setIgnoreComponentInstances(false);
522 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter, true);
523 if (validateComponentExists.isRight()) {
524 return Either.right(validateComponentExists.right().value());
527 containerComponent = validateComponentExists.left().value();
529 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
530 if (validateCanWorkOnComponent.isRight()) {
531 return Either.right(validateCanWorkOnComponent.right().value());
534 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
536 for (ComponentInstance componentInstance : componentInstanceList) {
537 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
538 if (!validateParent) {
539 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
540 containerComponentId));
547 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
548 if (lockComponent.isRight()) {
549 return Either.right(lockComponent.right().value());
553 List<ComponentInstance> updatedList = new ArrayList<>();
554 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
555 List<ComponentInstance> listForUpdate = new ArrayList<>();
556 if(instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
557 containerComponent.setComponentInstances(componentInstanceList);
559 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
560 while(iterator.hasNext()){
561 ComponentInstance origInst = iterator.next();
562 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
564 ComponentInstance updatedCi = op.get();
565 updatedCi.setCustomizationUUID(origInst.getCustomizationUUID());
566 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
568 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
569 origInst.getName(), updatedCi.getName());
570 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
574 listForUpdate.add(updatedCi);
577 listForUpdate.add(origInst);
579 containerComponent.setComponentInstances(listForUpdate);
581 if(resultOp == null){
582 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
583 if(updateStatus.isRight()){
584 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
585 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
588 for(ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()){
589 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
591 updatedList.add(updatedInstance);
597 resultOp = Either.left(updatedList);
602 unlockComponent(resultOp, containerComponent);
607 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
608 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
611 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
612 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
613 return ComponentTypeEnum.SERVICE_INSTANCE;
615 return ComponentTypeEnum.RESOURCE_INSTANCE;
619 private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
620 ComponentInstance componentInstance, boolean inTransaction) {
622 Either<ComponentInstance, ResponseFormat> resultOp = null;
623 Optional<ComponentInstance> componentInstanceOptional = null;
624 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
625 ComponentInstance oldComponentInstance = null;
626 boolean isNameChanged = false;
628 if (resultOp == null) {
629 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
630 if (!componentInstanceOptional.isPresent()) {
631 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
632 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
635 if (resultOp == null) {
636 oldComponentInstance = componentInstanceOptional.get();
637 String newInstanceName = componentInstance.getName();
638 if ( oldComponentInstance!=null && oldComponentInstance.getName() != null
639 && !oldComponentInstance.getName().equals( newInstanceName ) )
640 isNameChanged = true;
641 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
643 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);
644 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
647 if (resultOp == null) {
648 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
649 if (updateRes.isRight()) {
650 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
651 updateRes.right().value());
652 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
654 //region - Update instance Groups
655 if ( isNameChanged ){
656 Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance( containerComponent ,oldComponentInstance ,componentInstanceId );
657 if ( result.isRight() )
658 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId ,result.right().value() );
663 if (resultOp == null) {
664 String newInstanceId = updateRes.left().value().getRight();
665 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
667 if (!updatedInstanceOptional.isPresent()) {
668 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
669 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
671 resultOp = Either.left(updatedInstanceOptional.get());
675 if (resultOp == null) {
676 resultOp = Either.left(componentInstanceOptional.get());
681 * @param oldPrefix- The normalized old vf name
682 * @param newNormailzedPrefix- The normalized new vf name
683 * @param qualifiedGroupInstanceName- old Group Instance Name
686 private String getNewGroupName( String oldPrefix ,String newNormailzedPrefix , String qualifiedGroupInstanceName){
687 if (qualifiedGroupInstanceName == null){
688 log.info("CANNOT change group name ");
691 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
692 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
693 return qualifiedGroupInstanceName;
696 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
697 oldComponentInstance.setName(newComponentInstance.getName());
698 oldComponentInstance.setModificationTime(System.currentTimeMillis());
699 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
700 if ( oldComponentInstance.getGroupInstances() != null )
701 oldComponentInstance.getGroupInstances().forEach( group ->
702 group.setName( getNewGroupName( oldComponentInstance.getNormalizedName() , ValidationUtils.normalizeComponentInstanceName( newComponentInstance.getName() ) , group.getName() ) ) );
703 return oldComponentInstance;
706 public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
708 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
709 if (resp.isRight()) {
710 return Either.right(resp.right().value());
713 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
714 if (validateComponentType.isRight()) {
715 return Either.right(validateComponentType.right().value());
718 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
719 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
720 if (validateComponentExists.isRight()) {
721 return Either.right(validateComponentExists.right().value());
723 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
724 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
725 if (validateCanWorkOnComponent.isRight()) {
726 return Either.right(validateCanWorkOnComponent.right().value());
729 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
730 if (lockComponent.isRight()) {
731 return Either.right(lockComponent.right().value());
735 * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils
736 * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) {
737 * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; }
739 Either<ComponentInstance, ResponseFormat> resultOp = null;
741 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
746 * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service);
748 unlockComponent(resultOp, containerComponent);
752 private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
754 Either<ComponentInstance, ResponseFormat> resultOp = null;
755 ComponentInstance deletedInstance = null;
756 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
758 if (deleteRes.isRight()) {
759 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
760 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
761 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
763 if (resultOp == null) {
764 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
765 deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
766 resultOp = Either.left(deletedInstance);
768 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
769 List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
770 for(GroupDataDefinition currGroup : containerComponent.getGroups()){
771 if(currGroup.getMembers().containsKey(deletedInstance.getName())){
772 currGroup.getMembers().remove(deletedInstance.getName());
773 groupsToUpdate.add(currGroup);
776 Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes =
777 toscaOperationFacade.updateGroupsOnComponent(containerComponent, containerComponent.getComponentType(), groupsToUpdate);
778 if (updateGroupsRes.isRight()) {
779 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
780 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
781 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
784 if(resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())){
785 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
786 if(CollectionUtils.isNotEmpty(inputsToDelete)){
787 StorageOperationStatus deleteInputsRes =
788 toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
789 if(deleteInputsRes != StorageOperationStatus.OK){
790 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
791 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
798 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
799 ComponentInstance foundInstance = null;
800 for(ComponentInstance instance : containerComponent.getComponentInstances()){
801 if(instance.getUniqueId().equals(componentInstanceId)){
802 foundInstance = instance;
803 containerComponent.getComponentInstances().remove(instance);
807 return foundInstance;
810 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
811 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
814 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
815 boolean createNewTransaction) {
817 Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction);
818 if (resp.isRight()) {
819 return Either.right(resp.right().value());
822 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
824 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
825 if (validateComponentExists.isRight()) {
826 return Either.right(validateComponentExists.right().value());
828 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
830 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
831 if (validateCanWorkOnComponent.isRight()) {
832 return Either.right(validateCanWorkOnComponent.right().value());
835 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
837 if (lockComponent.isRight()) {
838 return Either.right(lockComponent.right().value());
844 resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
850 unlockComponent(resultOp, containerComponent);
854 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
856 log.debug("Try to create entry on graph");
857 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
859 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
861 if (result.isLeft()) {
862 log.debug("Enty on graph is created.");
863 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
864 resultOp = Either.left(requirementCapabilityRelDef);
868 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
869 String fromNameOrId = "";
870 String toNameOrId = "";
871 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
872 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
874 toNameOrId = requirementDef.getFromNode();
875 fromNameOrId = requirementDef.getFromNode();
876 if (fromResult.isLeft()) {
877 fromNameOrId = fromResult.left().value().getName();
879 if (toResult.isLeft()) {
880 toNameOrId = toResult.left().value().getName();
883 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement()));
890 public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
891 Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false);
892 if (resp.isRight()) {
893 return Either.right(resp.right().value());
896 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
897 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
898 if (validateComponentExists.isRight()) {
899 return Either.right(validateComponentExists.right().value());
901 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
903 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
904 if (validateCanWorkOnComponent.isRight()) {
905 return Either.right(validateCanWorkOnComponent.right().value());
907 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
909 if (lockComponent.isRight()) {
910 return Either.right(lockComponent.right().value());
913 log.debug("Try to create entry on graph");
914 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
915 if (result.isLeft()) {
916 log.debug("Enty on graph is created.");
917 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
918 resultOp = Either.left(requirementCapabilityRelDef);
923 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
924 String fromNameOrId = "";
925 String toNameOrId = "";
926 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
927 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
929 toNameOrId = requirementDef.getFromNode();
930 fromNameOrId = requirementDef.getFromNode();
931 if (fromResult.isLeft()) {
932 fromNameOrId = fromResult.left().value().getName();
934 if (toResult.isLeft()) {
935 toNameOrId = toResult.left().value().getName();
939 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement()));
943 unlockComponent(resultOp, containerComponent);
947 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
948 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
949 Either<ComponentInstanceProperty, ResponseFormat> result;
950 if (eitherAttribute.isLeft()) {
951 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
952 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
954 result = Either.left(instanceAttribute);
957 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
959 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
961 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
967 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
969 Either<ComponentInstanceProperty, ResponseFormat> result;
971 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
972 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
973 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
975 if (!errorWrapper.isEmpty()) {
976 result = Either.right(errorWrapper.getInnerElement());
978 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
979 if (eitherAttribute.isLeft()) {
980 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
981 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
982 result = Either.left(instanceAttribute);
985 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
987 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
988 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
996 * Create Or Updates Attribute Instance
998 * @param componentTypeEnum
1000 * @param resourceInstanceId
1005 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1006 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1007 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1009 validateUserExist(userId, "create Or Update Attribute Value", errorWrapper);
1010 if (errorWrapper.isEmpty()) {
1011 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1013 if (errorWrapper.isEmpty()) {
1014 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1016 if (errorWrapper.isEmpty()) {
1017 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1021 if (errorWrapper.isEmpty()) {
1022 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1024 result = createAttributeValue(attribute, resourceInstanceId);
1026 result = updateAttributeValue(attribute, resourceInstanceId);
1029 result = Either.right(errorWrapper.getInnerElement());
1035 if (result == null || result.isRight()) {
1036 titanDao.rollback();
1041 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1045 // US833308 VLI in service - specific network_role property value logic
1046 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) {
1047 if (StringUtils.isNotEmpty(property.getValue()) && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) && ComponentTypeEnum.SERVICE == componentTypeEnum) {
1048 ComponentParametersView componentParametersView = new ComponentParametersView();
1049 componentParametersView.disableAll();
1050 componentParametersView.setIgnoreComponentInstances(false);
1051 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1052 if (getServiceResult.isRight()) {
1053 return getServiceResult.right().value();
1055 Component service = getServiceResult.left().value();
1056 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1057 if (!getInstance.isPresent()) {
1058 return StorageOperationStatus.NOT_FOUND;
1060 String prefix = service.getSystemName() + ".";
1061 String value = property.getValue();
1062 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1063 property.setValue(prefix + value);
1066 return StorageOperationStatus.OK;
1069 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) {
1071 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1073 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1074 if (resp.isRight()) {
1075 return Either.right(resp.right().value());
1078 if (componentTypeEnum == null) {
1079 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1080 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1083 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1085 if (getResourceResult.isRight()) {
1086 log.debug("Failed to retrieve component, component id {}", componentId);
1087 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1090 Component containerComponent = getResourceResult.left().value();
1092 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1093 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1094 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1097 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1098 if (resourceInstanceStatus.isRight()) {
1099 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1102 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1103 // specific property value logic US833308
1104 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertyValue(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, property);
1105 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1106 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1110 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1111 if (lockStatus != StorageOperationStatus.OK) {
1112 log.debug("Failed to lock service {}", componentId);
1113 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1116 String innerType = null;
1117 String propertyType = property.getType();
1118 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1119 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1121 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1122 SchemaDefinition def = property.getSchema();
1124 log.debug("Schema doesn't exists for property of type {}", type);
1125 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1127 PropertyDataDefinition propDef = def.getProperty();
1128 if (propDef == null) {
1129 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1130 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1132 innerType = propDef.getType();
1134 // Specific Update Logic
1135 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
1136 if (allDataTypes.isRight()) {
1137 TitanOperationStatus status = allDataTypes.right().value();
1138 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1139 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1141 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
1143 String newValue = property.getValue();
1144 if (isValid.isRight()) {
1145 Boolean res = isValid.right().value();
1147 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1150 Object object = isValid.left().value();
1151 if (object != null) {
1152 newValue = object.toString();
1156 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes.left().value(), true);
1157 if (pair.getRight() != null && pair.getRight() == false) {
1158 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1159 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1163 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId);
1164 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1165 StorageOperationStatus status;
1166 instanceProperty.get().setValue(newValue);
1167 if(instanceProperty.isPresent()){
1168 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1170 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1172 if(status != StorageOperationStatus.OK){
1173 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1174 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1177 List<String> path = new ArrayList<>();
1178 path.add(foundResourceInstance.getUniqueId());
1179 property.setPath(path);
1181 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1182 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1184 if (updateContainerRes.isRight()) {
1185 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1186 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1189 resultOp = Either.left(property);
1193 if (resultOp == null || resultOp.isRight()) {
1194 titanDao.rollback();
1199 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1204 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInstanceInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput property, String userId) {
1206 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1208 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1209 if (resp.isRight()) {
1210 return Either.right(resp.right().value());
1213 if (componentTypeEnum == null) {
1214 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1215 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1218 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1220 if (getResourceResult.isRight()) {
1221 log.debug("Failed to retrieve component, component id {}", componentId);
1222 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1225 Component containerComponent = getResourceResult.left().value();
1227 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1228 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1229 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1232 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1233 if (resourceInstanceStatus.isRight()) {
1234 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1238 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1241 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1242 if (lockStatus != StorageOperationStatus.OK) {
1243 log.debug("Failed to lock service {}", componentId);
1244 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1247 String innerType = null;
1248 String propertyType = property.getType();
1249 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1250 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1252 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1253 SchemaDefinition def = property.getSchema();
1255 log.debug("Schema doesn't exists for property of type {}", type);
1256 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1258 PropertyDataDefinition propDef = def.getProperty();
1259 if (propDef == null) {
1260 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1261 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1263 innerType = propDef.getType();
1265 // Specific Update Logic
1266 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
1267 if (allDataTypes.isRight()) {
1268 TitanOperationStatus status = allDataTypes.right().value();
1269 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1270 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1272 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
1274 String newValue = property.getValue();
1275 if (isValid.isRight()) {
1276 Boolean res = isValid.right().value();
1278 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1281 Object object = isValid.left().value();
1282 if (object != null) {
1283 newValue = object.toString();
1288 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(resourceInstanceId);
1289 Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1290 StorageOperationStatus status;
1291 if(instanceProperty.isPresent()){
1292 instanceProperty.get().setValue(property.getValue());
1293 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
1295 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
1297 if(status != StorageOperationStatus.OK){
1298 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1299 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1302 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1303 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1305 if (updateContainerRes.isRight()) {
1306 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1307 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1310 resultOp = Either.left(property);
1314 if (resultOp == null || resultOp.isRight()) {
1315 titanDao.rollback();
1320 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1325 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1328 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1330 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1331 if (resp.isRight()) {
1332 return Either.right(resp.right().value());
1335 if (componentTypeEnum == null) {
1336 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1337 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1341 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1342 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1343 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1347 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1348 if (lockStatus != StorageOperationStatus.OK) {
1349 log.debug("Failed to lock service {}", componentId);
1350 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1354 String propertyValueUid = property.getValueUniqueUid();
1356 if (propertyValueUid == null) {
1358 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1360 if (counterRes.isRight()) {
1361 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1362 StorageOperationStatus status = counterRes.right().value();
1363 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1364 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1366 Integer index = counterRes.left().value();
1367 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1369 if (result.isLeft()) {
1370 log.trace("Property value was added to resource instance {}", resourceInstanceId);
1371 ComponentInstanceProperty instanceProperty = result.left().value();
1373 resultOp = Either.left(instanceProperty);
1376 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1378 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1380 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1384 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1386 if (result.isLeft()) {
1387 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1388 ComponentInstanceProperty instanceProperty = result.left().value();
1390 resultOp = Either.left(instanceProperty);
1393 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1395 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1397 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1400 if (resultOp.isLeft()) {
1401 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1402 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1403 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1405 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1412 if (resultOp == null || resultOp.isRight()) {
1413 titanDao.rollback();
1418 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1423 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1425 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1427 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false);
1428 if (resp.isRight()) {
1429 return Either.right(resp.right().value());
1432 if (componentTypeEnum == null) {
1433 BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
1434 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1438 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1439 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1440 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1444 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1445 if (lockStatus != StorageOperationStatus.OK) {
1446 log.debug("Failed to lock service {}", componentId);
1447 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1451 String propertyValueUid = inputProperty.getValueUniqueUid();
1452 if (propertyValueUid == null) {
1454 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1456 if (counterRes.isRight()) {
1457 log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1458 StorageOperationStatus status = counterRes.right().value();
1459 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1460 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1462 Integer index = counterRes.left().value();
1463 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1465 if (result.isLeft()) {
1466 log.debug("Property value was added to resource instance {}", resourceInstanceId);
1467 ComponentInstanceInput instanceProperty = result.left().value();
1469 resultOp = Either.left(instanceProperty);
1473 log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1475 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1477 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1483 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1485 if (result.isLeft()) {
1486 log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1487 ComponentInstanceInput instanceProperty = result.left().value();
1489 resultOp = Either.left(instanceProperty);
1493 log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
1495 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1497 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1504 if (resultOp == null || resultOp.isRight()) {
1505 titanDao.rollback();
1510 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1515 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1517 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false);
1518 if (resp.isRight()) {
1519 return Either.right(resp.right().value());
1522 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1524 if (componentTypeEnum == null) {
1525 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1526 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1530 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
1531 log.info("Restricted operation for user {} on service {}", userId, serviceId);
1532 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1536 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1537 if (lockStatus != StorageOperationStatus.OK) {
1538 log.debug("Failed to lock service {}", serviceId);
1539 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1543 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1545 if (result.isLeft()) {
1546 log.debug("Property value {} was removed from graph.", propertyValueId);
1547 ComponentInstanceProperty instanceProperty = result.left().value();
1549 resultOp = Either.left(instanceProperty);
1553 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1555 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1557 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1563 if (resultOp == null || resultOp.isRight()) {
1564 titanDao.rollback();
1569 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1574 private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1576 Either<Component, ResponseFormat> eitherResponse = null;
1577 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
1578 Component component;
1579 ResponseFormat errorResponse;
1580 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
1581 if (getComponentRes.isRight()) {
1582 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
1583 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
1584 errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1585 eitherResponse = Either.right(errorResponse);
1587 if(eitherResponse == null) {
1588 component = getComponentRes.left().value();
1589 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
1590 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
1591 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
1592 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
1593 eitherResponse = Either.right(errorResponse);
1596 if(eitherResponse == null) {
1597 eitherResponse = Either.left(getComponentRes.left().value());
1599 return eitherResponse;
1602 public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
1604 Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false);
1605 if (resp.isRight()) {
1606 return Either.right(resp.right().value());
1609 User user = resp.left().value();
1610 Either<ComponentInstance, ResponseFormat> resultOp = null;
1612 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
1613 if (validateComponentType.isRight()) {
1614 return Either.right(validateComponentType.right().value());
1617 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
1619 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
1620 if (validateComponentExists.isRight()) {
1621 return Either.right(validateComponentExists.right().value());
1623 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1625 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1626 if (validateCanWorkOnComponent.isRight()) {
1627 return Either.right(validateCanWorkOnComponent.right().value());
1630 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,componentInstanceId);
1631 if (resourceInstanceStatus.isRight()) {
1632 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
1636 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
1638 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
1639 if (lockComponent.isRight()) {
1640 return Either.right(lockComponent.right().value());
1644 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
1645 resultOp = Either.left(currentResourceInstance);
1649 String resourceId = newComponentInstance.getComponentUid();
1650 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
1651 if(componentExistsRes.isRight()){
1652 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
1653 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
1656 else if (!componentExistsRes.left().value()) {
1657 log.debug("The resource {} not found ", resourceId);
1658 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
1662 // List<GroupInstance> groupInstances = currentResourceInstance.getGroupInstances();
1663 Map<String, ArtifactDefinition> deploymentArtifacts = currentResourceInstance.getDeploymentArtifacts();
1664 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1665 if (resultOp.isRight()) {
1666 log.debug("failed to delete resource instance {}", resourceId);
1670 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(newComponentInstance, true);
1672 if (eitherResourceName.isRight()) {
1673 resultOp = Either.right(eitherResourceName.right().value());
1677 Component origComponent = eitherResourceName.left().value();
1679 ComponentInstance resResourceInfo = resultOp.left().value();
1680 newComponentInstance.setName(resResourceInfo.getName());
1681 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
1682 newComponentInstance.setPosX(resResourceInfo.getPosX());
1683 newComponentInstance.setPosY(resResourceInfo.getPosY());
1684 newComponentInstance.setDescription(resResourceInfo.getDescription());
1685 newComponentInstance.setToscaComponentName(((ResourceMetadataDataDefinition)origComponent.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName());
1687 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
1689 if (resultOp.isRight()) {
1690 log.debug("failed to create resource instance {}", resourceId);
1694 ComponentInstance updatedComponentInstance = resultOp.left().value();
1695 if (resultOp.isRight()) {
1696 log.debug("failed to create resource instance {}", resourceId);
1700 /* if (CollectionUtils.isNotEmpty(groupInstances)) {
1701 StorageOperationStatus addGroupsToComponentInstance = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, updatedComponentInstance, groupInstances);
1702 if (addGroupsToComponentInstance != StorageOperationStatus.OK) {
1703 BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR);
1704 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1710 if (MapUtils.isNotEmpty(deploymentArtifacts)) {
1711 StorageOperationStatus addDeploymentArtifactsToComponentInstance = toscaOperationFacade.addDeploymentArtifactsToComponentInstance(containerComponent, updatedComponentInstance, deploymentArtifacts);
1712 if (addDeploymentArtifactsToComponentInstance != StorageOperationStatus.OK) {
1713 BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR);
1714 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1720 ComponentParametersView filter = new ComponentParametersView(true);
1721 filter.setIgnoreComponentInstances(false);
1722 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1723 if (updatedComponentRes.isRight()) {
1724 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
1725 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
1726 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1727 log.debug("Component with id {} was not found", containerComponentId);
1728 return Either.right(responseFormat);
1730 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),updatedComponentInstance.getUniqueId());
1731 if (resourceInstanceStatus.isRight()) {
1732 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
1735 resultOp = Either.left(resourceInstanceStatus.left().value());
1739 unlockComponent(resultOp, containerComponent);
1743 protected abstract NodeTypeEnum getNodeTypeOfComponentInstanceOrigin();
1745 protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance();
1748 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
1749 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
1750 Component containerComponent = null;
1752 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1754 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
1755 if (validateUserExists.isRight()) {
1756 resultOp = Either.right(validateUserExists.right().value());
1760 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
1761 if (validateComponentType.isRight()) {
1762 resultOp = Either.right(validateComponentType.right().value());
1766 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
1767 if (validateContainerComponentExists.isRight()) {
1768 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
1771 containerComponent = validateContainerComponentExists.left().value();
1773 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
1774 if (resourceInstanceStatus.isRight()) {
1775 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
1779 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
1780 if(CollectionUtils.isEmpty(instanceProperties)){
1781 instanceProperties = new ArrayList<>();
1783 resultOp = Either.left(instanceProperties);
1786 unlockComponent(resultOp, containerComponent);
1790 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
1791 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
1793 if (counterRes.isRight()) {
1794 log.debug("increase And Get {} failed resource instance {}", counterType.name(), resourceInstanceId);
1795 StorageOperationStatus status = counterRes.right().value();
1796 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1797 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
1799 instaceCounterWrapper.setInnerElement(counterRes.left().value());
1805 * updates componentInstance modificationTime
1807 * @param componentInstance
1808 * @param componentInstanceType
1809 * @param modificationTime
1810 * @param inTransaction
1813 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
1814 Either<ComponentInstanceData, ResponseFormat> result;
1815 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
1817 if (updateComponentInstanceRes.isRight()) {
1818 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
1819 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
1821 result = Either.left(updateComponentInstanceRes.left().value());
1826 private Boolean validateInstanceNameUniqueness(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
1827 Boolean isUnique = true;
1828 String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
1829 if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
1830 Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
1831 if (foundComponentInstance.isPresent()) {
1835 foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().endsWith(newInstanceNormalizedName)).findFirst();
1836 if (foundComponentInstance.isPresent()) {
1844 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
1845 Boolean isUnique = true;
1846 String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
1847 if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
1848 Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
1849 if (foundComponentInstance.isPresent()) {
1856 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
1858 Either<ComponentInstance, StorageOperationStatus> result = null;
1859 List<ComponentInstance> instances = containerComponent.getComponentInstances();
1860 Optional<ComponentInstance> foundInstance = null;
1861 if(CollectionUtils.isEmpty(instances)){
1862 result = Either.right(StorageOperationStatus.NOT_FOUND);
1865 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1866 if(!foundInstance.isPresent()){
1867 result = Either.right(StorageOperationStatus.NOT_FOUND);
1871 result = Either.left(foundInstance.get());