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.lang.StringUtils;
36 import org.apache.commons.lang3.tuple.ImmutablePair;
37 import org.openecomp.sdc.be.config.BeEcompErrorManager;
38 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
39 import org.openecomp.sdc.be.dao.api.ActionStatus;
40 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
41 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
42 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
43 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
44 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
47 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
48 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
49 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
50 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
51 import org.openecomp.sdc.be.model.ArtifactDefinition;
52 import org.openecomp.sdc.be.model.Component;
53 import org.openecomp.sdc.be.model.ComponentInstance;
54 import org.openecomp.sdc.be.model.ComponentInstanceInput;
55 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
56 import org.openecomp.sdc.be.model.ComponentParametersView;
57 import org.openecomp.sdc.be.model.DataTypeDefinition;
58 import org.openecomp.sdc.be.model.GroupDefinition;
59 import org.openecomp.sdc.be.model.InputDefinition;
60 import org.openecomp.sdc.be.model.LifecycleStateEnum;
61 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
62 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
63 import org.openecomp.sdc.be.model.User;
64 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
65 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
66 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
67 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
68 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
69 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
70 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
71 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
72 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
73 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
74 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
75 import org.openecomp.sdc.common.api.Constants;
76 import org.openecomp.sdc.common.datastructure.Wrapper;
77 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
78 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
79 import org.openecomp.sdc.common.util.ValidationUtils;
80 import org.openecomp.sdc.exception.ResponseFormat;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83 import org.springframework.beans.factory.annotation.Autowired;
85 import fj.data.Either;
87 public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
89 private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName());
92 private IComponentInstanceOperation componentInstanceOperation;
95 private ArtifactsBusinessLogic artifactBusinessLogic;
97 private ApplicationDataTypeCache dataTypeCache;
99 public static final String VF_MODULE = "org.openecomp.groups.VfModule";
101 public ComponentInstanceBusinessLogic() {
104 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
105 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
108 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
110 Component origComponent = null;
111 Either<ComponentInstance, ResponseFormat> resultOp = null;
113 org.openecomp.sdc.be.model.Component containerComponent = null;
114 ComponentTypeEnum containerComponentType;
117 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
118 if (resp.isRight()) {
119 return Either.right(resp.right().value());
121 user = resp.left().value();
124 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
125 if (validateValidJson.isRight()) {
126 return Either.right(validateValidJson.right().value());
129 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
130 if (validateComponentType.isRight()) {
131 return Either.right(validateComponentType.right().value());
133 containerComponentType = validateComponentType.left().value();
136 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
137 if (validateComponentExists.isRight()) {
138 return Either.right(validateComponentExists.right().value());
140 containerComponent = validateComponentExists.left().value();
143 if (ModelConverter.isAtomicComponent(containerComponent)) {
144 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
145 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
148 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
149 if (validateCanWorkOnComponent.isRight()) {
150 return Either.right(validateCanWorkOnComponent.right().value());
153 if (resourceInstance != null && containerComponentType != null) {
154 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
155 if (getOriginComponentRes.isRight()) {
156 return Either.right(getOriginComponentRes.right().value());
158 origComponent = getOriginComponentRes.left().value();
162 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
163 if (lockComponent.isRight()) {
164 return Either.right(lockComponent.right().value());
167 log.debug("Try to create entry on graph");
168 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
173 unlockComponent(resultOp, containerComponent);
177 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
179 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
180 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
181 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
183 Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false);
184 if (resp.isRight()) {
185 return Either.right(resp.right().value());
188 User user = resp.left().value();
189 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
190 if (validateComponentType.isRight()) {
191 return Either.right(validateComponentType.right().value());
194 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
196 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
197 if (validateComponentExists.isRight()) {
198 return Either.right(validateComponentExists.right().value());
200 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
202 if (ModelConverter.isAtomicComponent(containerComponent)) {
203 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
204 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
207 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
208 if (validateCanWorkOnComponent.isRight()) {
209 return Either.right(validateCanWorkOnComponent.right().value());
212 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
213 if (lockComponent.isRight()) {
214 return Either.right(lockComponent.right().value());
218 log.debug("Try to create entry on graph");
219 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, true);
221 if (eitherResourceName.isRight()) {
222 resultOp = Either.right(eitherResourceName.right().value());
225 Component origComponent = eitherResourceName.left().value();
227 Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
228 if (result.isRight()) {
229 log.debug("Failed to create resource instance {}", containerComponentId);
230 resultOp = Either.right(result.right().value());
235 log.debug("Entity on graph is created.");
236 ComponentInstance resResourceInfo = result.left().value();
237 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
238 associationInfo.setFromNode(resResourceInfo.getUniqueId());
240 associationInfo.setToNode(resResourceInfo.getUniqueId());
243 RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo);
244 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
245 if (resultReqCapDef.isLeft()) {
246 log.debug("Enty on graph is created.");
247 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
248 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
249 resultOp = Either.left(resInfo);
253 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
254 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
259 unlockComponent(resultOp, containerComponent);
263 private Either<Component, ResponseFormat> getOriginComponentNameFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) {
264 Either<Component, ResponseFormat> eitherResponse;
265 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
266 if (eitherComponent.isRight()) {
267 log.debug("Failed to get origin component with id {} for component instance {} ", componentInstance.getComponentUid(), componentInstance.getName());
268 eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
270 eitherResponse = Either.left(eitherComponent.left().value());
272 return eitherResponse;
275 private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
276 Either<ComponentInstance, ResponseFormat> resultOp;
278 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
280 if (result.isRight()) {
281 log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
282 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
286 log.debug("Entity on graph is created.");
287 Component updatedComponent = result.left().value().getLeft();
288 Map<String, String> existingEnvVersions = new HashMap<>();
289 //TODO existingEnvVersions ??
290 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
291 if (addComponentInstanceArtifacts.isRight()) {
292 log.debug("Failed to create component instance {}", componentInstance.getName());
293 resultOp = Either.right(addComponentInstanceArtifacts.right().value());
297 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
298 if (!updatedInstanceOptional.isPresent()) {
299 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
300 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
303 resultOp = Either.left(updatedInstanceOptional.get());
308 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
310 * @param componentInstance
312 * @param existingEnvVersions
314 * @param containerComponentId
318 protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user,
319 Map<String, String> existingEnvVersions) {
320 log.debug("add artifacts to resource instance");
321 List<GroupDefinition> filteredGroups = null;
322 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
323 if (!ActionStatus.OK.equals(status)) {
324 ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
325 return Either.right(resultOp);
328 // generate heat_env if necessary
329 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
330 if (componentDeploymentArtifacts == null) {
331 return Either.left(ActionStatus.OK);
333 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
335 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
337 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
338 String type = artifact.getArtifactType();
340 if ( !type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) ){
341 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
344 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
348 if (artifact.checkEsIdExist()) {
349 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
350 componentInstance.getName(), user, containerComponent, existingEnvVersions);
351 if (createHeatEnvPlaceHolder.isRight()) {
352 return Either.right(createHeatEnvPlaceHolder.right().value());
354 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
357 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
359 if(CollectionUtils.isNotEmpty(originComponent.getGroups())){
360 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
362 if (CollectionUtils.isNotEmpty(filteredGroups)) {
363 for (GroupDefinition groupInstance : filteredGroups) {
364 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
365 if (op.isPresent()) {
366 List<ArtifactDefinition> artifactsUid;
367 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
368 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
370 artifactsUid = new ArrayList<>();
372 artifactsUid.add(artifactDefinition);
373 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
381 StorageOperationStatus artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
382 if ( artStatus != StorageOperationStatus.OK){
383 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
384 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
387 StorageOperationStatus result = toscaOperationFacade
388 .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
389 if (result != StorageOperationStatus.OK) {
390 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
391 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
393 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
396 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
397 if ( artStatus != StorageOperationStatus.OK){
398 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
399 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
402 componentInstance.setArtifacts(originComponent.getArtifacts());
403 return Either.left(ActionStatus.OK);
406 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
407 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null);
409 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
410 if (getResourceDeploymentArtifacts.isRight()) {
411 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
412 if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
413 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
414 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
417 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
420 if (!deploymentArtifacts.isEmpty()) {
421 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
422 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
423 if (!artifact.getValue().checkEsIdExist()) {
424 tempDeploymentArtifacts.remove(artifact.getKey());
428 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
431 return ActionStatus.OK;
434 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
435 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
438 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
439 boolean needLock, boolean createNewTransaction) {
441 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
442 if (resp.isRight()) {
443 return Either.right(resp.right().value());
446 Either<ComponentInstance, ResponseFormat> resultOp = null;
448 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
449 if (validateComponentType.isRight()) {
450 return Either.right(validateComponentType.right().value());
453 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
455 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
456 if (validateComponentExists.isRight()) {
457 return Either.right(validateComponentExists.right().value());
459 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
461 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
462 if (validateCanWorkOnComponent.isRight()) {
463 return Either.right(validateCanWorkOnComponent.right().value());
465 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
466 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
467 if (validateParentStatus.isRight()) {
468 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
469 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
472 if (!validateParentStatus.left().value()) {
473 resultOp = Either.right(
474 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
479 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
480 if (lockComponent.isRight()) {
481 return Either.right(lockComponent.right().value());
486 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
488 if (eitherResourceName.isRight()) {
489 resultOp = Either.right(eitherResourceName.right().value());
492 Component origComponent = eitherResourceName.left().value();
494 resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
499 unlockComponent(resultOp, containerComponent);
503 // New Multiple Instance Update API
504 public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock,
505 boolean createNewTransaction) {
507 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
508 org.openecomp.sdc.be.model.Component containerComponent = null;
510 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true);
511 if (resp.isRight()) {
512 return Either.right(resp.right().value());
515 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
516 if (validateComponentType.isRight()) {
517 return Either.right(validateComponentType.right().value());
520 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
522 ComponentParametersView componentFilter = new ComponentParametersView();
523 componentFilter.disableAll();
524 componentFilter.setIgnoreUsers(false);
525 componentFilter.setIgnoreComponentInstances(false);
526 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter, true);
527 if (validateComponentExists.isRight()) {
528 return Either.right(validateComponentExists.right().value());
531 containerComponent = validateComponentExists.left().value();
533 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
534 if (validateCanWorkOnComponent.isRight()) {
535 return Either.right(validateCanWorkOnComponent.right().value());
538 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
540 for (ComponentInstance componentInstance : componentInstanceList) {
541 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
542 if (!validateParent) {
543 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
544 containerComponentId));
551 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
552 if (lockComponent.isRight()) {
553 return Either.right(lockComponent.right().value());
557 List<ComponentInstance> updatedList = new ArrayList<>();
558 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
559 List<ComponentInstance> listForUpdate = new ArrayList<>();
560 if(instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
561 containerComponent.setComponentInstances(componentInstanceList);
563 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
564 while(iterator.hasNext()){
565 ComponentInstance origInst = iterator.next();
566 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
568 ComponentInstance updatedCi = op.get();
569 updatedCi = buildComponentInstance(updatedCi, origInst);
571 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
573 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
574 origInst.getName(), updatedCi.getName());
575 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
579 listForUpdate.add(updatedCi);
582 listForUpdate.add(origInst);
584 containerComponent.setComponentInstances(listForUpdate);
586 if(resultOp == null){
587 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
588 if(updateStatus.isRight()){
589 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
590 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
593 for(ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()){
594 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
596 updatedList.add(updatedInstance);
602 resultOp = Either.left(updatedList);
607 unlockComponent(resultOp, containerComponent);
612 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
613 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
616 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
617 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
618 return ComponentTypeEnum.SERVICE_INSTANCE;
620 return ComponentTypeEnum.RESOURCE_INSTANCE;
624 private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
625 ComponentInstance componentInstance) {
627 Either<ComponentInstance, ResponseFormat> resultOp = null;
628 Optional<ComponentInstance> componentInstanceOptional = null;
629 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
630 ComponentInstance oldComponentInstance = null;
631 boolean isNameChanged = false;
633 if (resultOp == null) {
634 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
635 if (!componentInstanceOptional.isPresent()) {
636 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
637 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
640 if (resultOp == null) {
641 oldComponentInstance = componentInstanceOptional.get();
642 String newInstanceName = componentInstance.getName();
643 if ( oldComponentInstance!=null && oldComponentInstance.getName() != null
644 && !oldComponentInstance.getName().equals( newInstanceName ) )
645 isNameChanged = true;
646 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
648 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);
649 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
652 if (resultOp == null) {
653 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
654 if (updateRes.isRight()) {
655 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
656 updateRes.right().value());
657 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
659 //region - Update instance Groups
660 if ( isNameChanged ){
661 Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance( containerComponent ,oldComponentInstance ,componentInstanceId );
662 if ( result.isRight() )
663 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId ,result.right().value() );
668 if (resultOp == null) {
669 String newInstanceId = updateRes.left().value().getRight();
670 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
672 if (!updatedInstanceOptional.isPresent()) {
673 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
674 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
676 resultOp = Either.left(updatedInstanceOptional.get());
680 if (resultOp == null) {
681 resultOp = Either.left(componentInstanceOptional.get());
686 * @param oldPrefix- The normalized old vf name
687 * @param newNormailzedPrefix- The normalized new vf name
688 * @param qualifiedGroupInstanceName- old Group Instance Name
691 private String getNewGroupName( String oldPrefix ,String newNormailzedPrefix , String qualifiedGroupInstanceName){
692 if (qualifiedGroupInstanceName == null){
693 log.info("CANNOT change group name ");
696 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
697 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
698 return qualifiedGroupInstanceName;
701 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
702 oldComponentInstance.setName(newComponentInstance.getName());
703 oldComponentInstance.setModificationTime(System.currentTimeMillis());
704 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
705 if ( oldComponentInstance.getGroupInstances() != null )
706 oldComponentInstance.getGroupInstances().forEach( group ->
707 group.setName( getNewGroupName( oldComponentInstance.getNormalizedName() , ValidationUtils.normalizeComponentInstanceName( newComponentInstance.getName() ) , group.getName() ) ) );
708 return oldComponentInstance;
711 public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
713 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
714 if (resp.isRight()) {
715 return Either.right(resp.right().value());
718 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
719 if (validateComponentType.isRight()) {
720 return Either.right(validateComponentType.right().value());
723 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
724 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
725 if (validateComponentExists.isRight()) {
726 return Either.right(validateComponentExists.right().value());
728 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
729 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
730 if (validateCanWorkOnComponent.isRight()) {
731 return Either.right(validateCanWorkOnComponent.right().value());
734 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
735 if (lockComponent.isRight()) {
736 return Either.right(lockComponent.right().value());
740 * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils
741 * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) {
742 * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; }
744 Either<ComponentInstance, ResponseFormat> resultOp = null;
746 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
751 * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service);
753 unlockComponent(resultOp, containerComponent);
757 private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
759 Either<ComponentInstance, ResponseFormat> resultOp = null;
760 ComponentInstance deletedInstance = null;
761 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
763 if (deleteRes.isRight()) {
764 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
765 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
766 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
768 if (resultOp == null) {
769 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
770 deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
771 resultOp = Either.left(deletedInstance);
773 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
774 List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
775 for(GroupDataDefinition currGroup : containerComponent.getGroups()){
776 if(currGroup.getMembers().containsKey(deletedInstance.getName())){
777 currGroup.getMembers().remove(deletedInstance.getName());
778 groupsToUpdate.add(currGroup);
781 Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes =
782 toscaOperationFacade.updateGroupsOnComponent(containerComponent, containerComponent.getComponentType(), groupsToUpdate);
783 if (updateGroupsRes.isRight()) {
784 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
785 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
786 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
789 if(resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())){
790 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
791 if(CollectionUtils.isNotEmpty(inputsToDelete)){
792 StorageOperationStatus deleteInputsRes =
793 toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
794 if(deleteInputsRes != StorageOperationStatus.OK){
795 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
796 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
803 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
804 ComponentInstance foundInstance = null;
805 for(ComponentInstance instance : containerComponent.getComponentInstances()){
806 if(instance.getUniqueId().equals(componentInstanceId)){
807 foundInstance = instance;
808 containerComponent.getComponentInstances().remove(instance);
812 return foundInstance;
815 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
816 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
819 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
820 boolean createNewTransaction) {
822 Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction);
823 if (resp.isRight()) {
824 return Either.right(resp.right().value());
827 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
829 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
830 if (validateComponentExists.isRight()) {
831 return Either.right(validateComponentExists.right().value());
833 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
835 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
836 if (validateCanWorkOnComponent.isRight()) {
837 return Either.right(validateCanWorkOnComponent.right().value());
840 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
842 if (lockComponent.isRight()) {
843 return Either.right(lockComponent.right().value());
849 resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
855 unlockComponent(resultOp, containerComponent);
859 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
861 log.debug("Try to create entry on graph");
862 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
864 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
866 if (result.isLeft()) {
867 log.debug("Enty on graph is created.");
868 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
869 resultOp = Either.left(requirementCapabilityRelDef);
873 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
874 String fromNameOrId = "";
875 String toNameOrId = "";
876 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
877 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
879 toNameOrId = requirementDef.getFromNode();
880 fromNameOrId = requirementDef.getFromNode();
881 if (fromResult.isLeft()) {
882 fromNameOrId = fromResult.left().value().getName();
884 if (toResult.isLeft()) {
885 toNameOrId = toResult.left().value().getName();
888 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement()));
895 public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
896 Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false);
897 if (resp.isRight()) {
898 return Either.right(resp.right().value());
901 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
902 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
903 if (validateComponentExists.isRight()) {
904 return Either.right(validateComponentExists.right().value());
906 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
908 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
909 if (validateCanWorkOnComponent.isRight()) {
910 return Either.right(validateCanWorkOnComponent.right().value());
912 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
914 if (lockComponent.isRight()) {
915 return Either.right(lockComponent.right().value());
918 log.debug("Try to create entry on graph");
919 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
920 if (result.isLeft()) {
921 log.debug("Enty on graph is created.");
922 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
923 resultOp = Either.left(requirementCapabilityRelDef);
928 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
929 String fromNameOrId = "";
930 String toNameOrId = "";
931 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
932 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
934 toNameOrId = requirementDef.getFromNode();
935 fromNameOrId = requirementDef.getFromNode();
936 if (fromResult.isLeft()) {
937 fromNameOrId = fromResult.left().value().getName();
939 if (toResult.isLeft()) {
940 toNameOrId = toResult.left().value().getName();
944 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement()));
948 unlockComponent(resultOp, containerComponent);
952 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
953 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
954 Either<ComponentInstanceProperty, ResponseFormat> result;
955 if (eitherAttribute.isLeft()) {
956 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
957 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
959 result = Either.left(instanceAttribute);
962 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
964 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
966 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
972 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
974 Either<ComponentInstanceProperty, ResponseFormat> result;
976 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
977 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
978 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
980 if (!errorWrapper.isEmpty()) {
981 result = Either.right(errorWrapper.getInnerElement());
983 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
984 if (eitherAttribute.isLeft()) {
985 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
986 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
987 result = Either.left(instanceAttribute);
990 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
992 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
993 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1001 * Create Or Updates Attribute Instance
1003 * @param componentTypeEnum
1004 * @param componentId
1005 * @param resourceInstanceId
1010 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1011 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1012 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1014 validateUserExist(userId, "create Or Update Attribute Value", errorWrapper);
1015 if (errorWrapper.isEmpty()) {
1016 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1018 if (errorWrapper.isEmpty()) {
1019 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1021 if (errorWrapper.isEmpty()) {
1022 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1026 if (errorWrapper.isEmpty()) {
1027 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1029 result = createAttributeValue(attribute, resourceInstanceId);
1031 result = updateAttributeValue(attribute, resourceInstanceId);
1034 result = Either.right(errorWrapper.getInnerElement());
1040 if (result == null || result.isRight()) {
1041 titanDao.rollback();
1046 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1050 // US833308 VLI in service - specific network_role property value logic
1051 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) {
1052 if (StringUtils.isNotEmpty(property.getValue()) && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) && ComponentTypeEnum.SERVICE == componentTypeEnum) {
1053 ComponentParametersView componentParametersView = new ComponentParametersView();
1054 componentParametersView.disableAll();
1055 componentParametersView.setIgnoreComponentInstances(false);
1056 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1057 if (getServiceResult.isRight()) {
1058 return getServiceResult.right().value();
1060 Component service = getServiceResult.left().value();
1061 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1062 if (!getInstance.isPresent()) {
1063 return StorageOperationStatus.NOT_FOUND;
1065 String prefix = service.getSystemName() + ".";
1066 String value = property.getValue();
1067 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1068 property.setValue(prefix + value);
1071 return StorageOperationStatus.OK;
1074 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) {
1076 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1078 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1079 if (resp.isRight()) {
1080 return Either.right(resp.right().value());
1083 if (componentTypeEnum == null) {
1084 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1085 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1088 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1090 if (getResourceResult.isRight()) {
1091 log.debug("Failed to retrieve component, component id {}", componentId);
1092 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1095 Component containerComponent = getResourceResult.left().value();
1097 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1098 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1099 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1102 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1103 if (resourceInstanceStatus.isRight()) {
1104 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1107 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1108 // specific property value logic US833308
1109 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertyValue(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, property);
1110 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1111 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1115 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1116 if (lockStatus != StorageOperationStatus.OK) {
1117 log.debug("Failed to lock service {}", componentId);
1118 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1121 String innerType = null;
1122 String propertyType = property.getType();
1123 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1124 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1126 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1127 SchemaDefinition def = property.getSchema();
1129 log.debug("Schema doesn't exists for property of type {}", type);
1130 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1132 PropertyDataDefinition propDef = def.getProperty();
1133 if (propDef == null) {
1134 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1135 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1137 innerType = propDef.getType();
1139 // Specific Update Logic
1140 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
1141 if (allDataTypes.isRight()) {
1142 TitanOperationStatus status = allDataTypes.right().value();
1143 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1144 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1146 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
1148 String newValue = property.getValue();
1149 if (isValid.isRight()) {
1150 Boolean res = isValid.right().value();
1152 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1155 Object object = isValid.left().value();
1156 if (object != null) {
1157 newValue = object.toString();
1161 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes.left().value(), true);
1162 if (pair.getRight() != null && pair.getRight() == false) {
1163 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1164 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1168 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId);
1169 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1170 StorageOperationStatus status;
1171 instanceProperty.get().setValue(newValue);
1172 if(instanceProperty.isPresent()){
1173 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1175 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1177 if(status != StorageOperationStatus.OK){
1178 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1179 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1182 List<String> path = new ArrayList<>();
1183 path.add(foundResourceInstance.getUniqueId());
1184 property.setPath(path);
1186 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1187 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1189 if (updateContainerRes.isRight()) {
1190 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1191 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1194 resultOp = Either.left(property);
1198 if (resultOp == null || resultOp.isRight()) {
1199 titanDao.rollback();
1204 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1209 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInstanceInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput property, String userId) {
1211 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1213 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1214 if (resp.isRight()) {
1215 return Either.right(resp.right().value());
1218 if (componentTypeEnum == null) {
1219 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1220 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1223 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1225 if (getResourceResult.isRight()) {
1226 log.debug("Failed to retrieve component, component id {}", componentId);
1227 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1230 Component containerComponent = getResourceResult.left().value();
1232 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1233 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1234 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1237 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1238 if (resourceInstanceStatus.isRight()) {
1239 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1243 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1246 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1247 if (lockStatus != StorageOperationStatus.OK) {
1248 log.debug("Failed to lock service {}", componentId);
1249 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1252 String innerType = null;
1253 String propertyType = property.getType();
1254 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1255 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1257 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1258 SchemaDefinition def = property.getSchema();
1260 log.debug("Schema doesn't exists for property of type {}", type);
1261 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1263 PropertyDataDefinition propDef = def.getProperty();
1264 if (propDef == null) {
1265 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1266 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1268 innerType = propDef.getType();
1270 // Specific Update Logic
1271 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
1272 if (allDataTypes.isRight()) {
1273 TitanOperationStatus status = allDataTypes.right().value();
1274 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1275 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1277 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
1279 String newValue = property.getValue();
1280 if (isValid.isRight()) {
1281 Boolean res = isValid.right().value();
1283 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1286 Object object = isValid.left().value();
1287 if (object != null) {
1288 newValue = object.toString();
1293 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(resourceInstanceId);
1294 Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1295 StorageOperationStatus status;
1296 if(instanceProperty.isPresent()){
1297 instanceProperty.get().setValue(property.getValue());
1298 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
1300 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
1302 if(status != StorageOperationStatus.OK){
1303 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1304 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1307 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1308 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1310 if (updateContainerRes.isRight()) {
1311 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1312 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1315 resultOp = Either.left(property);
1319 if (resultOp == null || resultOp.isRight()) {
1320 titanDao.rollback();
1325 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1330 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1333 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1335 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1336 if (resp.isRight()) {
1337 return Either.right(resp.right().value());
1340 if (componentTypeEnum == null) {
1341 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1342 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1346 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1347 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1348 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1352 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1353 if (lockStatus != StorageOperationStatus.OK) {
1354 log.debug("Failed to lock service {}", componentId);
1355 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1359 String propertyValueUid = property.getValueUniqueUid();
1361 if (propertyValueUid == null) {
1363 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1365 if (counterRes.isRight()) {
1366 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1367 StorageOperationStatus status = counterRes.right().value();
1368 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1369 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1371 Integer index = counterRes.left().value();
1372 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1374 if (result.isLeft()) {
1375 log.trace("Property value was added to resource instance {}", resourceInstanceId);
1376 ComponentInstanceProperty instanceProperty = result.left().value();
1378 resultOp = Either.left(instanceProperty);
1381 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1383 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1385 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1389 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1391 if (result.isLeft()) {
1392 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1393 ComponentInstanceProperty instanceProperty = result.left().value();
1395 resultOp = Either.left(instanceProperty);
1398 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1400 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1402 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1405 if (resultOp.isLeft()) {
1406 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1407 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1408 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1410 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1417 if (resultOp == null || resultOp.isRight()) {
1418 titanDao.rollback();
1423 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1428 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1430 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1432 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false);
1433 if (resp.isRight()) {
1434 return Either.right(resp.right().value());
1437 if (componentTypeEnum == null) {
1438 BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
1439 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1443 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1444 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1445 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1449 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1450 if (lockStatus != StorageOperationStatus.OK) {
1451 log.debug("Failed to lock service {}", componentId);
1452 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1456 String propertyValueUid = inputProperty.getValueUniqueUid();
1457 if (propertyValueUid == null) {
1459 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1461 if (counterRes.isRight()) {
1462 log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1463 StorageOperationStatus status = counterRes.right().value();
1464 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1465 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1467 Integer index = counterRes.left().value();
1468 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1470 if (result.isLeft()) {
1471 log.debug("Property value was added to resource instance {}", resourceInstanceId);
1472 ComponentInstanceInput instanceProperty = result.left().value();
1474 resultOp = Either.left(instanceProperty);
1478 log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1480 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1482 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1488 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1490 if (result.isLeft()) {
1491 log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1492 ComponentInstanceInput instanceProperty = result.left().value();
1494 resultOp = Either.left(instanceProperty);
1498 log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
1500 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1502 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1509 if (resultOp == null || resultOp.isRight()) {
1510 titanDao.rollback();
1515 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1520 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1522 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false);
1523 if (resp.isRight()) {
1524 return Either.right(resp.right().value());
1527 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1529 if (componentTypeEnum == null) {
1530 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1531 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1535 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
1536 log.info("Restricted operation for user {} on service {}", userId, serviceId);
1537 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1541 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1542 if (lockStatus != StorageOperationStatus.OK) {
1543 log.debug("Failed to lock service {}", serviceId);
1544 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1548 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1550 if (result.isLeft()) {
1551 log.debug("Property value {} was removed from graph.", propertyValueId);
1552 ComponentInstanceProperty instanceProperty = result.left().value();
1554 resultOp = Either.left(instanceProperty);
1558 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1560 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1562 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1568 if (resultOp == null || resultOp.isRight()) {
1569 titanDao.rollback();
1574 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1579 private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1581 Either<Component, ResponseFormat> eitherResponse = null;
1582 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
1583 Component component;
1584 ResponseFormat errorResponse;
1585 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
1586 if (getComponentRes.isRight()) {
1587 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
1588 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
1589 errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1590 eitherResponse = Either.right(errorResponse);
1592 if(eitherResponse == null) {
1593 component = getComponentRes.left().value();
1594 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
1595 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
1596 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
1597 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
1598 eitherResponse = Either.right(errorResponse);
1601 if(eitherResponse == null) {
1602 eitherResponse = Either.left(getComponentRes.left().value());
1604 return eitherResponse;
1607 public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
1609 Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false);
1610 if (resp.isRight()) {
1611 return Either.right(resp.right().value());
1614 User user = resp.left().value();
1615 Either<ComponentInstance, ResponseFormat> resultOp = null;
1617 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
1618 if (validateComponentType.isRight()) {
1619 return Either.right(validateComponentType.right().value());
1622 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
1624 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
1625 if (validateComponentExists.isRight()) {
1626 return Either.right(validateComponentExists.right().value());
1628 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1630 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1631 if (validateCanWorkOnComponent.isRight()) {
1632 return Either.right(validateCanWorkOnComponent.right().value());
1635 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,componentInstanceId);
1636 if (resourceInstanceStatus.isRight()) {
1637 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
1641 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
1643 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
1644 if (lockComponent.isRight()) {
1645 return Either.right(lockComponent.right().value());
1649 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
1650 resultOp = Either.left(currentResourceInstance);
1654 String resourceId = newComponentInstance.getComponentUid();
1655 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
1656 if(componentExistsRes.isRight()){
1657 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
1658 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
1661 else if (!componentExistsRes.left().value()) {
1662 log.debug("The resource {} not found ", resourceId);
1663 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
1667 // List<GroupInstance> groupInstances = currentResourceInstance.getGroupInstances();
1668 Map<String, ArtifactDefinition> deploymentArtifacts = currentResourceInstance.getDeploymentArtifacts();
1669 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1670 if (resultOp.isRight()) {
1671 log.debug("failed to delete resource instance {}", resourceId);
1675 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(newComponentInstance, true);
1677 if (eitherResourceName.isRight()) {
1678 resultOp = Either.right(eitherResourceName.right().value());
1682 Component origComponent = eitherResourceName.left().value();
1684 ComponentInstance resResourceInfo = resultOp.left().value();
1685 newComponentInstance.setName(resResourceInfo.getName());
1686 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
1687 newComponentInstance.setPosX(resResourceInfo.getPosX());
1688 newComponentInstance.setPosY(resResourceInfo.getPosY());
1689 newComponentInstance.setDescription(resResourceInfo.getDescription());
1690 newComponentInstance.setToscaComponentName(((ResourceMetadataDataDefinition)origComponent.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName());
1692 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
1694 if (resultOp.isRight()) {
1695 log.debug("failed to create resource instance {}", resourceId);
1699 ComponentInstance updatedComponentInstance = resultOp.left().value();
1700 if (resultOp.isRight()) {
1701 log.debug("failed to create resource instance {}", resourceId);
1705 /* if (CollectionUtils.isNotEmpty(groupInstances)) {
1706 StorageOperationStatus addGroupsToComponentInstance = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, updatedComponentInstance, groupInstances);
1707 if (addGroupsToComponentInstance != StorageOperationStatus.OK) {
1708 BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR);
1709 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1715 if (MapUtils.isNotEmpty(deploymentArtifacts)) {
1716 StorageOperationStatus addDeploymentArtifactsToComponentInstance = toscaOperationFacade.addDeploymentArtifactsToComponentInstance(containerComponent, updatedComponentInstance, deploymentArtifacts);
1717 if (addDeploymentArtifactsToComponentInstance != 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 ComponentParametersView filter = new ComponentParametersView(true);
1726 filter.setIgnoreComponentInstances(false);
1727 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1728 if (updatedComponentRes.isRight()) {
1729 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
1730 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
1731 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1732 log.debug("Component with id {} was not found", containerComponentId);
1733 return Either.right(responseFormat);
1735 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),updatedComponentInstance.getUniqueId());
1736 if (resourceInstanceStatus.isRight()) {
1737 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
1740 resultOp = Either.left(resourceInstanceStatus.left().value());
1744 unlockComponent(resultOp, containerComponent);
1748 protected abstract NodeTypeEnum getNodeTypeOfComponentInstanceOrigin();
1750 protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance();
1753 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
1754 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
1755 Component containerComponent = null;
1757 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1759 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
1760 if (validateUserExists.isRight()) {
1761 resultOp = Either.right(validateUserExists.right().value());
1765 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
1766 if (validateComponentType.isRight()) {
1767 resultOp = Either.right(validateComponentType.right().value());
1771 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
1772 if (validateContainerComponentExists.isRight()) {
1773 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
1776 containerComponent = validateContainerComponentExists.left().value();
1778 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
1779 if (resourceInstanceStatus.isRight()) {
1780 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
1784 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
1785 if(CollectionUtils.isEmpty(instanceProperties)){
1786 instanceProperties = new ArrayList<>();
1788 resultOp = Either.left(instanceProperties);
1791 unlockComponent(resultOp, containerComponent);
1795 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
1796 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
1798 if (counterRes.isRight()) {
1799 log.debug("increase And Get {} failed resource instance {}", counterType.name(), resourceInstanceId);
1800 StorageOperationStatus status = counterRes.right().value();
1801 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1802 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
1804 instaceCounterWrapper.setInnerElement(counterRes.left().value());
1810 * updates componentInstance modificationTime
1812 * @param componentInstance
1813 * @param componentInstanceType
1814 * @param modificationTime
1815 * @param inTransaction
1818 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
1819 Either<ComponentInstanceData, ResponseFormat> result;
1820 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
1822 if (updateComponentInstanceRes.isRight()) {
1823 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
1824 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
1826 result = Either.left(updateComponentInstanceRes.left().value());
1831 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
1832 // TODO Add implementation
1833 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
1837 public Either<ComponentInstance, ResponseFormat> createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) {
1838 // TODO Add implementation
1839 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
1843 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
1844 // TODO Add implementation
1845 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
1849 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
1850 Boolean isUnique = true;
1851 String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
1852 if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
1853 Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
1854 if (foundComponentInstance.isPresent()) {
1861 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
1863 Either<ComponentInstance, StorageOperationStatus> result = null;
1864 List<ComponentInstance> instances = containerComponent.getComponentInstances();
1865 Optional<ComponentInstance> foundInstance = null;
1866 if(CollectionUtils.isEmpty(instances)){
1867 result = Either.right(StorageOperationStatus.NOT_FOUND);
1870 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1871 if(!foundInstance.isPresent()){
1872 result = Either.right(StorageOperationStatus.NOT_FOUND);
1876 result = Either.left(foundInstance.get());
1881 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
1883 Long creationDate = origInstanceForUpdate.getCreationTime();
1885 Long modificationTime = System.currentTimeMillis();
1886 resourceInstanceForUpdate.setCreationTime(creationDate);
1887 resourceInstanceForUpdate.setModificationTime(modificationTime);
1889 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
1891 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
1892 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
1895 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
1897 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
1898 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
1901 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
1902 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
1904 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
1905 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
1907 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
1908 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
1910 if (resourceInstanceForUpdate.getOriginType() == null) {
1911 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
1913 return resourceInstanceForUpdate;