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.ComponentInstanceDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
49 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
51 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
52 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
53 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
54 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
55 import org.openecomp.sdc.be.model.ArtifactDefinition;
56 import org.openecomp.sdc.be.model.Component;
57 import org.openecomp.sdc.be.model.ComponentInstance;
58 import org.openecomp.sdc.be.model.ComponentInstanceInput;
59 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
60 import org.openecomp.sdc.be.model.ComponentParametersView;
61 import org.openecomp.sdc.be.model.DataTypeDefinition;
62 import org.openecomp.sdc.be.model.GroupDefinition;
63 import org.openecomp.sdc.be.model.GroupInstance;
64 import org.openecomp.sdc.be.model.InputDefinition;
65 import org.openecomp.sdc.be.model.LifecycleStateEnum;
66 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
67 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
68 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
69 import org.openecomp.sdc.be.model.Resource;
70 import org.openecomp.sdc.be.model.User;
71 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
72 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
73 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
74 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
75 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
76 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
77 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
78 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
79 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
80 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
81 import org.openecomp.sdc.be.resources.data.PropertyValueData;
82 import org.openecomp.sdc.be.tosca.ToscaUtils;
83 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
84 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
85 import org.openecomp.sdc.common.api.Constants;
86 import org.openecomp.sdc.common.datastructure.Wrapper;
87 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
88 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
89 import org.openecomp.sdc.common.util.ValidationUtils;
90 import org.openecomp.sdc.exception.ResponseFormat;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
93 import org.springframework.beans.factory.annotation.Autowired;
95 import fj.data.Either;
97 public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
99 private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName());
102 private IComponentInstanceOperation componentInstanceOperation;
105 private ArtifactsBusinessLogic artifactBusinessLogic;
107 private ApplicationDataTypeCache dataTypeCache;
109 public static final String VF_MODULE = "org.openecomp.groups.VfModule";
111 public ComponentInstanceBusinessLogic() {
114 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
115 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
118 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
120 Component origComponent = null;
121 Either<ComponentInstance, ResponseFormat> resultOp = null;
123 org.openecomp.sdc.be.model.Component containerComponent = null;
124 ComponentTypeEnum containerComponentType;
127 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
128 if (resp.isRight()) {
129 return Either.right(resp.right().value());
131 user = resp.left().value();
134 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
135 if (validateValidJson.isRight()) {
136 return Either.right(validateValidJson.right().value());
139 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
140 if (validateComponentType.isRight()) {
141 return Either.right(validateComponentType.right().value());
143 containerComponentType = validateComponentType.left().value();
146 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
147 if (validateComponentExists.isRight()) {
148 return Either.right(validateComponentExists.right().value());
150 containerComponent = validateComponentExists.left().value();
153 if (ToscaUtils.isAtomicType(containerComponent)) {
154 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
155 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
158 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
159 if (validateCanWorkOnComponent.isRight()) {
160 return Either.right(validateCanWorkOnComponent.right().value());
163 if (resourceInstance != null && containerComponentType != null) {
164 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
165 if (getOriginComponentRes.isRight()) {
166 return Either.right(getOriginComponentRes.right().value());
168 origComponent = getOriginComponentRes.left().value();
172 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
173 if (lockComponent.isRight()) {
174 return Either.right(lockComponent.right().value());
177 log.debug("Try to create entry on graph");
178 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
183 unlockComponent(resultOp, containerComponent);
187 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
189 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
190 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
191 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
193 Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false);
194 if (resp.isRight()) {
195 return Either.right(resp.right().value());
198 User user = resp.left().value();
199 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
200 if (validateComponentType.isRight()) {
201 return Either.right(validateComponentType.right().value());
204 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
206 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
207 if (validateComponentExists.isRight()) {
208 return Either.right(validateComponentExists.right().value());
210 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
212 if (ToscaUtils.isAtomicType(containerComponent)) {
213 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
214 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
217 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
218 if (validateCanWorkOnComponent.isRight()) {
219 return Either.right(validateCanWorkOnComponent.right().value());
222 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
223 if (lockComponent.isRight()) {
224 return Either.right(lockComponent.right().value());
228 log.debug("Try to create entry on graph");
229 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, true);
231 if (eitherResourceName.isRight()) {
232 resultOp = Either.right(eitherResourceName.right().value());
235 Component origComponent = eitherResourceName.left().value();
237 Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
238 if (result.isRight()) {
239 log.debug("Failed to create resource instance {}", containerComponentId);
240 resultOp = Either.right(result.right().value());
245 log.debug("Entity on graph is created.");
246 ComponentInstance resResourceInfo = result.left().value();
247 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
248 associationInfo.setFromNode(resResourceInfo.getUniqueId());
250 associationInfo.setToNode(resResourceInfo.getUniqueId());
253 RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo);
254 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
255 if (resultReqCapDef.isLeft()) {
256 log.debug("Enty on graph is created.");
257 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
258 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
259 resultOp = Either.left(resInfo);
263 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
264 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
269 unlockComponent(resultOp, containerComponent);
273 private Either<Component, ResponseFormat> getOriginComponentNameFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) {
274 Either<Component, ResponseFormat> eitherResponse;
275 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
276 if (eitherComponent.isRight()) {
277 log.debug("Failed to get origin component with id {} for component instance {} ", componentInstance.getComponentUid(), componentInstance.getName());
278 eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
280 eitherResponse = Either.left(eitherComponent.left().value());
282 return eitherResponse;
285 private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
286 Either<ComponentInstance, ResponseFormat> resultOp;
288 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
290 if (result.isRight()) {
291 log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
292 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
296 log.debug("Entity on graph is created.");
297 Component updatedComponent = result.left().value().getLeft();
298 Map<String, String> existingEnvVersions = new HashMap<>();
299 //TODO existingEnvVersions ??
300 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
301 if (addComponentInstanceArtifacts.isRight()) {
302 log.debug("Failed to create component instance {}", componentInstance.getName());
303 resultOp = Either.right(addComponentInstanceArtifacts.right().value());
307 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
308 if (!updatedInstanceOptional.isPresent()) {
309 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
310 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
313 resultOp = Either.left(updatedInstanceOptional.get());
318 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
320 * @param componentInstance
322 * @param existingEnvVersions
324 * @param containerComponentId
328 protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user,
329 Map<String, String> existingEnvVersions) {
330 log.debug("add artifacts to resource instance");
331 List<GroupDefinition> filteredGroups = null;
332 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
333 if (!ActionStatus.OK.equals(status)) {
334 ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
335 return Either.right(resultOp);
338 // generate heat_env if necessary
339 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
340 if (componentDeploymentArtifacts == null) {
341 return Either.left(ActionStatus.OK);
343 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
345 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
347 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
348 String type = artifact.getArtifactType();
350 if ( !type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) ){
351 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
354 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
358 if (artifact.checkEsIdExist()) {
359 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
360 componentInstance.getName(), user, containerComponent, existingEnvVersions);
361 if (createHeatEnvPlaceHolder.isRight()) {
362 return Either.right(createHeatEnvPlaceHolder.right().value());
364 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
367 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
369 if(CollectionUtils.isNotEmpty(originComponent.getGroups())){
370 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
372 if (CollectionUtils.isNotEmpty(filteredGroups)) {
373 for (GroupDefinition groupInstance : filteredGroups) {
374 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
375 if (op.isPresent()) {
376 List<ArtifactDefinition> artifactsUid;
377 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
378 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
380 artifactsUid = new ArrayList<>();
382 artifactsUid.add(artifactDefinition);
383 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
391 StorageOperationStatus artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
392 if ( artStatus != StorageOperationStatus.OK){
393 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
394 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
397 StorageOperationStatus result = toscaOperationFacade
398 .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
399 if (result != StorageOperationStatus.OK) {
400 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
401 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
403 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
406 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
407 if ( artStatus != StorageOperationStatus.OK){
408 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
409 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
412 componentInstance.setArtifacts(originComponent.getArtifacts());
413 return Either.left(ActionStatus.OK);
416 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
417 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null);
419 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
420 if (getResourceDeploymentArtifacts.isRight()) {
421 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
422 if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
423 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
424 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
427 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
430 if (!deploymentArtifacts.isEmpty()) {
431 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
432 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
433 if (!artifact.getValue().checkEsIdExist()) {
434 tempDeploymentArtifacts.remove(artifact.getKey());
438 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
441 return ActionStatus.OK;
444 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
445 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
448 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
449 boolean needLock, boolean createNewTransaction) {
451 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
452 if (resp.isRight()) {
453 return Either.right(resp.right().value());
456 Either<ComponentInstance, ResponseFormat> resultOp = null;
458 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
459 if (validateComponentType.isRight()) {
460 return Either.right(validateComponentType.right().value());
463 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
465 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
466 if (validateComponentExists.isRight()) {
467 return Either.right(validateComponentExists.right().value());
469 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
471 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
472 if (validateCanWorkOnComponent.isRight()) {
473 return Either.right(validateCanWorkOnComponent.right().value());
475 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
476 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
477 if (validateParentStatus.isRight()) {
478 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
479 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
482 if (!validateParentStatus.left().value()) {
483 resultOp = Either.right(
484 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
489 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
490 if (lockComponent.isRight()) {
491 return Either.right(lockComponent.right().value());
496 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
498 if (eitherResourceName.isRight()) {
499 resultOp = Either.right(eitherResourceName.right().value());
502 Component origComponent = eitherResourceName.left().value();
504 resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
509 unlockComponent(resultOp, containerComponent);
513 // New Multiple Instance Update API
514 public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock,
515 boolean createNewTransaction) {
517 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
518 org.openecomp.sdc.be.model.Component containerComponent = null;
520 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true);
521 if (resp.isRight()) {
522 return Either.right(resp.right().value());
525 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
526 if (validateComponentType.isRight()) {
527 return Either.right(validateComponentType.right().value());
530 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
532 ComponentParametersView componentFilter = new ComponentParametersView();
533 componentFilter.disableAll();
534 componentFilter.setIgnoreUsers(false);
535 componentFilter.setIgnoreComponentInstances(false);
536 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter, true);
537 if (validateComponentExists.isRight()) {
538 return Either.right(validateComponentExists.right().value());
541 containerComponent = validateComponentExists.left().value();
543 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
544 if (validateCanWorkOnComponent.isRight()) {
545 return Either.right(validateCanWorkOnComponent.right().value());
548 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
550 for (ComponentInstance componentInstance : componentInstanceList) {
551 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
552 if (!validateParent) {
553 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
554 containerComponentId));
561 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
562 if (lockComponent.isRight()) {
563 return Either.right(lockComponent.right().value());
567 List<ComponentInstance> updatedList = new ArrayList<>();
568 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
569 List<ComponentInstance> listForUpdate = new ArrayList<>();
570 if(instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
571 containerComponent.setComponentInstances(componentInstanceList);
573 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
574 while(iterator.hasNext()){
575 ComponentInstance origInst = iterator.next();
576 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
578 ComponentInstance updatedCi = op.get();
579 updatedCi = buildComponentInstance(updatedCi, origInst);
581 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
583 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
584 origInst.getName(), updatedCi.getName());
585 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
589 listForUpdate.add(updatedCi);
592 listForUpdate.add(origInst);
594 containerComponent.setComponentInstances(listForUpdate);
596 if(resultOp == null){
597 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
598 if(updateStatus.isRight()){
599 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
600 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
603 for(ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()){
604 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
606 updatedList.add(updatedInstance);
612 resultOp = Either.left(updatedList);
617 unlockComponent(resultOp, containerComponent);
622 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
623 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
626 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
627 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
628 return ComponentTypeEnum.SERVICE_INSTANCE;
630 return ComponentTypeEnum.RESOURCE_INSTANCE;
634 private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
635 ComponentInstance componentInstance) {
637 Either<ComponentInstance, ResponseFormat> resultOp = null;
638 Optional<ComponentInstance> componentInstanceOptional = null;
639 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
640 ComponentInstance oldComponentInstance = null;
641 boolean isNameChanged = false;
643 if (resultOp == null) {
644 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
645 if (!componentInstanceOptional.isPresent()) {
646 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
647 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
650 if (resultOp == null) {
651 oldComponentInstance = componentInstanceOptional.get();
652 String newInstanceName = componentInstance.getName();
653 if ( oldComponentInstance!=null && oldComponentInstance.getName() != null
654 && !oldComponentInstance.getName().equals( newInstanceName ) )
655 isNameChanged = true;
656 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
658 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);
659 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
662 if (resultOp == null) {
663 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
664 if (updateRes.isRight()) {
665 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
666 updateRes.right().value());
667 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
669 //region - Update instance Groups
670 if ( isNameChanged ){
671 Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance( containerComponent ,oldComponentInstance ,componentInstanceId );
672 if ( result.isRight() )
673 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId ,result.right().value() );
678 if (resultOp == null) {
679 String newInstanceId = updateRes.left().value().getRight();
680 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
682 if (!updatedInstanceOptional.isPresent()) {
683 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
684 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
686 resultOp = Either.left(updatedInstanceOptional.get());
690 if (resultOp == null) {
691 resultOp = Either.left(componentInstanceOptional.get());
696 * @param oldPrefix- The normalized old vf name
697 * @param newNormailzedPrefix- The normalized new vf name
698 * @param qualifiedGroupInstanceName- old Group Instance Name
701 private String getNewGroupName( String oldPrefix ,String newNormailzedPrefix , String qualifiedGroupInstanceName){
702 if (qualifiedGroupInstanceName == null){
703 log.info("CANNOT change group name ");
706 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
707 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
708 return qualifiedGroupInstanceName;
711 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
712 oldComponentInstance.setName(newComponentInstance.getName());
713 oldComponentInstance.setModificationTime(System.currentTimeMillis());
714 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
715 if ( oldComponentInstance.getGroupInstances() != null )
716 oldComponentInstance.getGroupInstances().forEach( group ->
717 group.setName( getNewGroupName( oldComponentInstance.getNormalizedName() , ValidationUtils.normalizeComponentInstanceName( newComponentInstance.getName() ) , group.getName() ) ) );
718 return oldComponentInstance;
721 public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
723 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
724 if (resp.isRight()) {
725 return Either.right(resp.right().value());
728 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
729 if (validateComponentType.isRight()) {
730 return Either.right(validateComponentType.right().value());
733 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
734 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
735 if (validateComponentExists.isRight()) {
736 return Either.right(validateComponentExists.right().value());
738 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
739 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
740 if (validateCanWorkOnComponent.isRight()) {
741 return Either.right(validateCanWorkOnComponent.right().value());
744 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
745 if (lockComponent.isRight()) {
746 return Either.right(lockComponent.right().value());
750 * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils
751 * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) {
752 * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; }
754 Either<ComponentInstance, ResponseFormat> resultOp = null;
756 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
761 * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service);
763 unlockComponent(resultOp, containerComponent);
767 private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
769 Either<ComponentInstance, ResponseFormat> resultOp = null;
770 ComponentInstance deletedInstance = null;
771 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
773 if (deleteRes.isRight()) {
774 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
775 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
776 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
778 if (resultOp == null) {
779 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
780 deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
781 resultOp = Either.left(deletedInstance);
783 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
784 List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
785 for(GroupDataDefinition currGroup : containerComponent.getGroups()){
786 if(currGroup.getMembers().containsKey(deletedInstance.getName())){
787 currGroup.getMembers().remove(deletedInstance.getName());
788 groupsToUpdate.add(currGroup);
791 Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes =
792 toscaOperationFacade.updateGroupsOnComponent(containerComponent, containerComponent.getComponentType(), groupsToUpdate);
793 if (updateGroupsRes.isRight()) {
794 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
795 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
796 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
799 if(resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())){
800 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
801 if(CollectionUtils.isNotEmpty(inputsToDelete)){
802 StorageOperationStatus deleteInputsRes =
803 toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
804 if(deleteInputsRes != StorageOperationStatus.OK){
805 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
806 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
813 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
814 ComponentInstance foundInstance = null;
815 for(ComponentInstance instance : containerComponent.getComponentInstances()){
816 if(instance.getUniqueId().equals(componentInstanceId)){
817 foundInstance = instance;
818 containerComponent.getComponentInstances().remove(instance);
822 return foundInstance;
825 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
826 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
829 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
830 boolean createNewTransaction) {
832 Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction);
833 if (resp.isRight()) {
834 return Either.right(resp.right().value());
837 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
839 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
840 if (validateComponentExists.isRight()) {
841 return Either.right(validateComponentExists.right().value());
843 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
845 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
846 if (validateCanWorkOnComponent.isRight()) {
847 return Either.right(validateCanWorkOnComponent.right().value());
850 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
852 if (lockComponent.isRight()) {
853 return Either.right(lockComponent.right().value());
859 resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
865 unlockComponent(resultOp, containerComponent);
869 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
871 log.debug("Try to create entry on graph");
872 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
874 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
876 if (result.isLeft()) {
877 log.debug("Enty on graph is created.");
878 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
879 resultOp = Either.left(requirementCapabilityRelDef);
883 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
884 String fromNameOrId = "";
885 String toNameOrId = "";
886 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
887 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
889 toNameOrId = requirementDef.getFromNode();
890 fromNameOrId = requirementDef.getFromNode();
891 if (fromResult.isLeft()) {
892 fromNameOrId = fromResult.left().value().getName();
894 if (toResult.isLeft()) {
895 toNameOrId = toResult.left().value().getName();
898 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement()));
905 public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
906 Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false);
907 if (resp.isRight()) {
908 return Either.right(resp.right().value());
911 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
912 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
913 if (validateComponentExists.isRight()) {
914 return Either.right(validateComponentExists.right().value());
916 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
918 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
919 if (validateCanWorkOnComponent.isRight()) {
920 return Either.right(validateCanWorkOnComponent.right().value());
922 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
924 if (lockComponent.isRight()) {
925 return Either.right(lockComponent.right().value());
928 log.debug("Try to create entry on graph");
929 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
930 if (result.isLeft()) {
931 log.debug("Enty on graph is created.");
932 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
933 resultOp = Either.left(requirementCapabilityRelDef);
938 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
939 String fromNameOrId = "";
940 String toNameOrId = "";
941 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
942 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
944 toNameOrId = requirementDef.getFromNode();
945 fromNameOrId = requirementDef.getFromNode();
946 if (fromResult.isLeft()) {
947 fromNameOrId = fromResult.left().value().getName();
949 if (toResult.isLeft()) {
950 toNameOrId = toResult.left().value().getName();
954 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement()));
958 unlockComponent(resultOp, containerComponent);
962 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
963 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
964 Either<ComponentInstanceProperty, ResponseFormat> result;
965 if (eitherAttribute.isLeft()) {
966 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
967 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
969 result = Either.left(instanceAttribute);
972 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
974 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
976 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
982 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
984 Either<ComponentInstanceProperty, ResponseFormat> result;
986 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
987 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
988 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
990 if (!errorWrapper.isEmpty()) {
991 result = Either.right(errorWrapper.getInnerElement());
993 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
994 if (eitherAttribute.isLeft()) {
995 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
996 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
997 result = Either.left(instanceAttribute);
1000 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1002 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1003 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1011 * Create Or Updates Attribute Instance
1013 * @param componentTypeEnum
1014 * @param componentId
1015 * @param resourceInstanceId
1020 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1021 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1022 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1024 validateUserExist(userId, "create Or Update Attribute Value", errorWrapper);
1025 if (errorWrapper.isEmpty()) {
1026 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1028 if (errorWrapper.isEmpty()) {
1029 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1031 if (errorWrapper.isEmpty()) {
1032 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1036 if (errorWrapper.isEmpty()) {
1037 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1039 result = createAttributeValue(attribute, resourceInstanceId);
1041 result = updateAttributeValue(attribute, resourceInstanceId);
1044 result = Either.right(errorWrapper.getInnerElement());
1050 if (result == null || result.isRight()) {
1051 titanDao.rollback();
1056 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1060 // US833308 VLI in service - specific network_role property value logic
1061 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) {
1062 if (StringUtils.isNotEmpty(property.getValue()) && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) && ComponentTypeEnum.SERVICE == componentTypeEnum) {
1063 ComponentParametersView componentParametersView = new ComponentParametersView();
1064 componentParametersView.disableAll();
1065 componentParametersView.setIgnoreComponentInstances(false);
1066 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1067 if (getServiceResult.isRight()) {
1068 return getServiceResult.right().value();
1070 Component service = getServiceResult.left().value();
1071 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1072 if (!getInstance.isPresent()) {
1073 return StorageOperationStatus.NOT_FOUND;
1075 String prefix = service.getSystemName() + ".";
1076 String value = property.getValue();
1077 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1078 property.setValue(prefix + value);
1081 return StorageOperationStatus.OK;
1084 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) {
1086 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1088 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1089 if (resp.isRight()) {
1090 return Either.right(resp.right().value());
1093 if (componentTypeEnum == null) {
1094 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1095 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1098 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1100 if (getResourceResult.isRight()) {
1101 log.debug("Failed to retrieve component, component id {}", componentId);
1102 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1105 Component containerComponent = getResourceResult.left().value();
1107 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1108 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1109 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1112 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1113 if (resourceInstanceStatus.isRight()) {
1114 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1117 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1118 // specific property value logic US833308
1119 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertyValue(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, property);
1120 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1121 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1125 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1126 if (lockStatus != StorageOperationStatus.OK) {
1127 log.debug("Failed to lock service {}", componentId);
1128 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1131 String innerType = null;
1132 String propertyType = property.getType();
1133 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1134 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1136 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1137 SchemaDefinition def = property.getSchema();
1139 log.debug("Schema doesn't exists for property of type {}", type);
1140 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1142 PropertyDataDefinition propDef = def.getProperty();
1143 if (propDef == null) {
1144 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1145 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1147 innerType = propDef.getType();
1149 // Specific Update Logic
1150 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
1151 if (allDataTypes.isRight()) {
1152 TitanOperationStatus status = allDataTypes.right().value();
1153 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1154 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1156 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
1158 String newValue = property.getValue();
1159 if (isValid.isRight()) {
1160 Boolean res = isValid.right().value();
1162 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1165 Object object = isValid.left().value();
1166 if (object != null) {
1167 newValue = object.toString();
1171 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes.left().value(), true);
1172 if (pair.getRight() != null && pair.getRight() == false) {
1173 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1174 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1178 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId);
1179 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1180 StorageOperationStatus status;
1181 instanceProperty.get().setValue(newValue);
1182 if(instanceProperty.isPresent()){
1183 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1185 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1187 if(status != StorageOperationStatus.OK){
1188 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1189 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1192 List<String> path = new ArrayList<>();
1193 path.add(foundResourceInstance.getUniqueId());
1194 property.setPath(path);
1196 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1197 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1199 if (updateContainerRes.isRight()) {
1200 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1201 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1204 resultOp = Either.left(property);
1208 if (resultOp == null || resultOp.isRight()) {
1209 titanDao.rollback();
1214 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1219 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInstanceInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput property, String userId) {
1221 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1223 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1224 if (resp.isRight()) {
1225 return Either.right(resp.right().value());
1228 if (componentTypeEnum == null) {
1229 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1230 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1233 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1235 if (getResourceResult.isRight()) {
1236 log.debug("Failed to retrieve component, component id {}", componentId);
1237 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1240 Component containerComponent = getResourceResult.left().value();
1242 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1243 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1244 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1247 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1248 if (resourceInstanceStatus.isRight()) {
1249 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1253 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1256 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1257 if (lockStatus != StorageOperationStatus.OK) {
1258 log.debug("Failed to lock service {}", componentId);
1259 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1262 String innerType = null;
1263 String propertyType = property.getType();
1264 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1265 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1267 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1268 SchemaDefinition def = property.getSchema();
1270 log.debug("Schema doesn't exists for property of type {}", type);
1271 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1273 PropertyDataDefinition propDef = def.getProperty();
1274 if (propDef == null) {
1275 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1276 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1278 innerType = propDef.getType();
1280 // Specific Update Logic
1281 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
1282 if (allDataTypes.isRight()) {
1283 TitanOperationStatus status = allDataTypes.right().value();
1284 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1285 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1287 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
1289 String newValue = property.getValue();
1290 if (isValid.isRight()) {
1291 Boolean res = isValid.right().value();
1293 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1296 Object object = isValid.left().value();
1297 if (object != null) {
1298 newValue = object.toString();
1303 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(resourceInstanceId);
1304 Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1305 StorageOperationStatus status;
1306 if(instanceProperty.isPresent()){
1307 instanceProperty.get().setValue(property.getValue());
1308 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
1310 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
1312 if(status != StorageOperationStatus.OK){
1313 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1314 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1317 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1318 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1320 if (updateContainerRes.isRight()) {
1321 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1322 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1325 resultOp = Either.left(property);
1329 if (resultOp == null || resultOp.isRight()) {
1330 titanDao.rollback();
1335 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1340 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1343 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1345 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1346 if (resp.isRight()) {
1347 return Either.right(resp.right().value());
1350 if (componentTypeEnum == null) {
1351 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1352 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1356 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1357 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1358 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1362 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1363 if (lockStatus != StorageOperationStatus.OK) {
1364 log.debug("Failed to lock service {}", componentId);
1365 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1369 String propertyValueUid = property.getValueUniqueUid();
1371 if (propertyValueUid == null) {
1373 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1375 if (counterRes.isRight()) {
1376 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1377 StorageOperationStatus status = counterRes.right().value();
1378 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1379 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1381 Integer index = counterRes.left().value();
1382 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1384 if (result.isLeft()) {
1385 log.trace("Property value was added to resource instance {}", resourceInstanceId);
1386 ComponentInstanceProperty instanceProperty = result.left().value();
1388 resultOp = Either.left(instanceProperty);
1391 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1393 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1395 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1399 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1401 if (result.isLeft()) {
1402 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1403 ComponentInstanceProperty instanceProperty = result.left().value();
1405 resultOp = Either.left(instanceProperty);
1408 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1410 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1412 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1415 if (resultOp.isLeft()) {
1416 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1417 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1418 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1420 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1427 if (resultOp == null || resultOp.isRight()) {
1428 titanDao.rollback();
1433 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1438 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1440 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1442 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false);
1443 if (resp.isRight()) {
1444 return Either.right(resp.right().value());
1447 if (componentTypeEnum == null) {
1448 BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
1449 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1453 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1454 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1455 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1459 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1460 if (lockStatus != StorageOperationStatus.OK) {
1461 log.debug("Failed to lock service {}", componentId);
1462 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1466 String propertyValueUid = inputProperty.getValueUniqueUid();
1467 if (propertyValueUid == null) {
1469 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1471 if (counterRes.isRight()) {
1472 log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1473 StorageOperationStatus status = counterRes.right().value();
1474 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1475 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1477 Integer index = counterRes.left().value();
1478 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1480 if (result.isLeft()) {
1481 log.debug("Property value was added to resource instance {}", resourceInstanceId);
1482 ComponentInstanceInput instanceProperty = result.left().value();
1484 resultOp = Either.left(instanceProperty);
1488 log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1490 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1492 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1498 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1500 if (result.isLeft()) {
1501 log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1502 ComponentInstanceInput instanceProperty = result.left().value();
1504 resultOp = Either.left(instanceProperty);
1508 log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
1510 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1512 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1519 if (resultOp == null || resultOp.isRight()) {
1520 titanDao.rollback();
1525 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1530 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1532 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false);
1533 if (resp.isRight()) {
1534 return Either.right(resp.right().value());
1537 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1539 if (componentTypeEnum == null) {
1540 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1541 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1545 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
1546 log.info("Restricted operation for user {} on service {}", userId, serviceId);
1547 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1551 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1552 if (lockStatus != StorageOperationStatus.OK) {
1553 log.debug("Failed to lock service {}", serviceId);
1554 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1558 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1560 if (result.isLeft()) {
1561 log.debug("Property value {} was removed from graph.", propertyValueId);
1562 ComponentInstanceProperty instanceProperty = result.left().value();
1564 resultOp = Either.left(instanceProperty);
1568 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1570 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1572 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1578 if (resultOp == null || resultOp.isRight()) {
1579 titanDao.rollback();
1584 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1589 private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1591 Either<Component, ResponseFormat> eitherResponse = null;
1592 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
1593 Component component;
1594 ResponseFormat errorResponse;
1595 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
1596 if (getComponentRes.isRight()) {
1597 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
1598 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
1599 errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1600 eitherResponse = Either.right(errorResponse);
1602 if(eitherResponse == null) {
1603 component = getComponentRes.left().value();
1604 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
1605 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
1606 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
1607 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
1608 eitherResponse = Either.right(errorResponse);
1611 if(eitherResponse == null) {
1612 eitherResponse = Either.left(getComponentRes.left().value());
1614 return eitherResponse;
1617 public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
1619 Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false);
1620 if (resp.isRight()) {
1621 return Either.right(resp.right().value());
1624 User user = resp.left().value();
1625 Either<ComponentInstance, ResponseFormat> resultOp = null;
1627 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
1628 if (validateComponentType.isRight()) {
1629 return Either.right(validateComponentType.right().value());
1632 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
1634 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
1635 if (validateComponentExists.isRight()) {
1636 return Either.right(validateComponentExists.right().value());
1638 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1640 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1641 if (validateCanWorkOnComponent.isRight()) {
1642 return Either.right(validateCanWorkOnComponent.right().value());
1645 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,componentInstanceId);
1646 if (resourceInstanceStatus.isRight()) {
1647 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
1651 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
1653 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
1654 if (lockComponent.isRight()) {
1655 return Either.right(lockComponent.right().value());
1659 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
1660 resultOp = Either.left(currentResourceInstance);
1664 String resourceId = newComponentInstance.getComponentUid();
1665 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
1666 if(componentExistsRes.isRight()){
1667 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
1668 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
1671 else if (!componentExistsRes.left().value()) {
1672 log.debug("The resource {} not found ", resourceId);
1673 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
1677 // List<GroupInstance> groupInstances = currentResourceInstance.getGroupInstances();
1678 Map<String, ArtifactDefinition> deploymentArtifacts = currentResourceInstance.getDeploymentArtifacts();
1679 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1680 if (resultOp.isRight()) {
1681 log.debug("failed to delete resource instance {}", resourceId);
1685 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(newComponentInstance, true);
1687 if (eitherResourceName.isRight()) {
1688 resultOp = Either.right(eitherResourceName.right().value());
1692 Component origComponent = eitherResourceName.left().value();
1694 ComponentInstance resResourceInfo = resultOp.left().value();
1695 newComponentInstance.setName(resResourceInfo.getName());
1696 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
1697 newComponentInstance.setPosX(resResourceInfo.getPosX());
1698 newComponentInstance.setPosY(resResourceInfo.getPosY());
1699 newComponentInstance.setDescription(resResourceInfo.getDescription());
1700 newComponentInstance.setToscaComponentName(((ResourceMetadataDataDefinition)origComponent.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName());
1702 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
1704 if (resultOp.isRight()) {
1705 log.debug("failed to create resource instance {}", resourceId);
1709 ComponentInstance updatedComponentInstance = resultOp.left().value();
1710 if (resultOp.isRight()) {
1711 log.debug("failed to create resource instance {}", resourceId);
1715 /* if (CollectionUtils.isNotEmpty(groupInstances)) {
1716 StorageOperationStatus addGroupsToComponentInstance = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, updatedComponentInstance, groupInstances);
1717 if (addGroupsToComponentInstance != StorageOperationStatus.OK) {
1718 BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR);
1719 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1725 if (MapUtils.isNotEmpty(deploymentArtifacts)) {
1726 StorageOperationStatus addDeploymentArtifactsToComponentInstance = toscaOperationFacade.addDeploymentArtifactsToComponentInstance(containerComponent, updatedComponentInstance, deploymentArtifacts);
1727 if (addDeploymentArtifactsToComponentInstance != StorageOperationStatus.OK) {
1728 BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR);
1729 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1735 ComponentParametersView filter = new ComponentParametersView(true);
1736 filter.setIgnoreComponentInstances(false);
1737 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1738 if (updatedComponentRes.isRight()) {
1739 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
1740 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
1741 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1742 log.debug("Component with id {} was not found", containerComponentId);
1743 return Either.right(responseFormat);
1745 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),updatedComponentInstance.getUniqueId());
1746 if (resourceInstanceStatus.isRight()) {
1747 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
1750 resultOp = Either.left(resourceInstanceStatus.left().value());
1754 unlockComponent(resultOp, containerComponent);
1758 protected abstract NodeTypeEnum getNodeTypeOfComponentInstanceOrigin();
1760 protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance();
1763 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
1764 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
1765 Component containerComponent = null;
1767 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1769 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
1770 if (validateUserExists.isRight()) {
1771 resultOp = Either.right(validateUserExists.right().value());
1775 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
1776 if (validateComponentType.isRight()) {
1777 resultOp = Either.right(validateComponentType.right().value());
1781 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
1782 if (validateContainerComponentExists.isRight()) {
1783 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
1786 containerComponent = validateContainerComponentExists.left().value();
1788 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
1789 if (resourceInstanceStatus.isRight()) {
1790 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
1794 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
1795 if(CollectionUtils.isEmpty(instanceProperties)){
1796 instanceProperties = new ArrayList<>();
1798 resultOp = Either.left(instanceProperties);
1801 unlockComponent(resultOp, containerComponent);
1805 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
1806 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
1808 if (counterRes.isRight()) {
1809 log.debug("increase And Get {} failed resource instance {}", counterType.name(), resourceInstanceId);
1810 StorageOperationStatus status = counterRes.right().value();
1811 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1812 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
1814 instaceCounterWrapper.setInnerElement(counterRes.left().value());
1820 * updates componentInstance modificationTime
1822 * @param componentInstance
1823 * @param componentInstanceType
1824 * @param modificationTime
1825 * @param inTransaction
1828 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
1829 Either<ComponentInstanceData, ResponseFormat> result;
1830 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
1832 if (updateComponentInstanceRes.isRight()) {
1833 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
1834 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
1836 result = Either.left(updateComponentInstanceRes.left().value());
1841 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
1842 // TODO Add implementation
1843 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
1847 public Either<ComponentInstance, ResponseFormat> createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) {
1848 // TODO Add implementation
1849 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
1853 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
1854 // TODO Add implementation
1855 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
1859 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
1860 Boolean isUnique = true;
1861 String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
1862 if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
1863 Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
1864 if (foundComponentInstance.isPresent()) {
1871 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
1873 Either<ComponentInstance, StorageOperationStatus> result = null;
1874 List<ComponentInstance> instances = containerComponent.getComponentInstances();
1875 Optional<ComponentInstance> foundInstance = null;
1876 if(CollectionUtils.isEmpty(instances)){
1877 result = Either.right(StorageOperationStatus.NOT_FOUND);
1880 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1881 if(!foundInstance.isPresent()){
1882 result = Either.right(StorageOperationStatus.NOT_FOUND);
1886 result = Either.left(foundInstance.get());
1891 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
1893 Long creationDate = origInstanceForUpdate.getCreationTime();
1895 Long modificationTime = System.currentTimeMillis();
1896 resourceInstanceForUpdate.setCreationTime(creationDate);
1897 resourceInstanceForUpdate.setModificationTime(modificationTime);
1899 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
1901 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
1902 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
1905 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
1907 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
1908 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
1911 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
1912 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
1914 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
1915 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
1917 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
1918 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
1920 if (resourceInstanceForUpdate.getOriginType() == null) {
1921 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
1923 return resourceInstanceForUpdate;