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=========================================================
19 * Modifications copyright (c) 2019 Nokia
20 * ================================================================================
23 package org.openecomp.sdc.be.components.impl;
25 import fj.data.Either;
26 import org.apache.commons.collections.CollectionUtils;
27 import org.apache.commons.collections.MapUtils;
28 import org.apache.commons.io.FilenameUtils;
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.commons.lang3.math.NumberUtils;
31 import org.apache.commons.lang3.tuple.ImmutablePair;
32 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
33 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
34 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
35 import org.openecomp.sdc.be.components.impl.lock.LockingTransactional;
36 import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdateHandler;
37 import org.openecomp.sdc.be.components.utils.Utils;
38 import org.openecomp.sdc.be.components.validation.AccessValidations;
39 import org.openecomp.sdc.be.components.validation.ComponentValidations;
40 import org.openecomp.sdc.be.config.BeEcompErrorManager;
41 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
42 import org.openecomp.sdc.be.config.ConfigurationManager;
43 import org.openecomp.sdc.be.dao.api.ActionStatus;
44 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
45 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
48 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
49 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
51 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
52 import org.openecomp.sdc.be.info.ArtifactDefinitionInfo;
53 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
54 import org.openecomp.sdc.be.info.GroupDefinitionInfo;
55 import org.openecomp.sdc.be.model.ArtifactDefinition;
56 import org.openecomp.sdc.be.model.Component;
57 import org.openecomp.sdc.be.model.ComponentInstance;
58 import org.openecomp.sdc.be.model.ComponentParametersView;
59 import org.openecomp.sdc.be.model.DataTypeDefinition;
60 import org.openecomp.sdc.be.model.GroupDefinition;
61 import org.openecomp.sdc.be.model.GroupInstance;
62 import org.openecomp.sdc.be.model.GroupInstanceProperty;
63 import org.openecomp.sdc.be.model.GroupProperty;
64 import org.openecomp.sdc.be.model.GroupTypeDefinition;
65 import org.openecomp.sdc.be.model.PropertyDefinition;
66 import org.openecomp.sdc.be.model.PropertyDefinition.GroupInstancePropertyValueUpdateBehavior;
67 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
68 import org.openecomp.sdc.be.model.Resource;
69 import org.openecomp.sdc.be.model.User;
70 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
71 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation;
72 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
73 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation;
74 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
75 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
76 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
77 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
78 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
79 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
80 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
81 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
82 import org.openecomp.sdc.common.api.Constants;
83 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
84 import org.openecomp.sdc.common.log.enums.LogLevel;
85 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
86 import org.openecomp.sdc.common.log.enums.StatusCode;
87 import org.openecomp.sdc.common.log.wrappers.Logger;
88 import org.openecomp.sdc.common.util.ValidationUtils;
89 import org.openecomp.sdc.exception.ResponseFormat;
90 import org.springframework.beans.factory.annotation.Autowired;
92 import java.util.ArrayList;
93 import java.util.Arrays;
94 import java.util.Collection;
95 import java.util.Collections;
96 import java.util.EnumMap;
97 import java.util.HashMap;
98 import java.util.List;
100 import java.util.Map.Entry;
101 import java.util.Optional;
102 import java.util.Set;
103 import java.util.regex.Pattern;
104 import java.util.stream.Collectors;
106 import static java.util.stream.Collectors.toList;
107 import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilitiesFromGroups;
108 import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilityPropertiesFromGroups;
110 @org.springframework.stereotype.Component("groupBusinessLogic")
111 public class GroupBusinessLogic extends BaseBusinessLogic {
113 public static final String GROUP_DELIMITER_REGEX = "\\.\\.";
115 public static final String INITIAL_VERSION = "0.0";
117 private static final String ADDING_GROUP = "AddingGroup";
119 private static final String CREATE_GROUP = "CreateGroup";
121 private static final String UPDATE_GROUP = "UpdateGroup";
123 private static final String GET_GROUP = "GetGroup";
125 private static final String DELETE_GROUP = "DeleteGroup";
127 private static final Logger log = Logger.getLogger(GroupBusinessLogic.class);
129 public LoggerSupportability loggerSupportability= LoggerSupportability.getLogger(GroupBusinessLogic.class.getName());
131 private final AccessValidations accessValidations;
132 private final PolicyTargetsUpdateHandler policyTargetsUpdateHandler;
134 @javax.annotation.Resource
135 private final GroupsOperation groupsOperation;
139 public GroupBusinessLogic(IElementOperation elementDao,
140 IGroupOperation groupOperation,
141 IGroupInstanceOperation groupInstanceOperation,
142 IGroupTypeOperation groupTypeOperation,
143 InterfaceOperation interfaceOperation,
144 InterfaceLifecycleOperation interfaceLifecycleTypeOperation, AccessValidations accessValidations,
145 GroupsOperation groupsOperation, PolicyTargetsUpdateHandler policyTargetsUpdateHandler,
146 ArtifactsOperations artifactToscaOperation) {
147 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
148 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
149 this.accessValidations = accessValidations;
150 this.groupsOperation = groupsOperation;
151 this.policyTargetsUpdateHandler = policyTargetsUpdateHandler;
154 private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) {
155 String componentTypeForResponse = "SERVICE";
156 if (component instanceof Resource) {
157 componentTypeForResponse = ((Resource) component).getResourceType().name();
159 return componentTypeForResponse;
163 * Verify that the artifact members belongs to the component
169 private Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) {
171 if (CollectionUtils.isEmpty(artifacts)) {
172 return Either.left(true);
175 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
176 if (MapUtils.isEmpty(deploymentArtifacts)) {
177 BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO);
178 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
181 List<String> currentArtifacts = deploymentArtifacts.values().stream().map(ArtifactDefinition::getUniqueId).collect(toList());
182 log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts);
183 if (!currentArtifacts.containsAll(artifacts)) {
184 BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
185 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
188 return Either.left(true);
193 * verify that the members are component instances of the component
196 * @param groupMembers
197 * @param memberToscaTypes
200 private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, String groupName, Map<String, String> groupMembers, List<String> memberToscaTypes) {
202 if (MapUtils.isEmpty(groupMembers)) {
203 return Either.left(true);
206 if (CollectionUtils.isEmpty(memberToscaTypes)) {
207 return Either.left(true);
210 List<ComponentInstance> componentInstances = component.getComponentInstances();
211 if (CollectionUtils.isNotEmpty(componentInstances)) {
212 Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getUniqueId, p -> p));
214 Set<String> allCompInstances = compInstUidToCompInstMap.keySet();
216 for (Entry<String, String> groupMember : groupMembers.entrySet()) {
217 String compName = groupMember.getKey();
218 String compUid = groupMember.getValue();
220 if (!allCompInstances.contains(compUid)) {
222 * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ]
224 String componentTypeForResponse = getComponentTypeForResponse(component);
226 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO);
227 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse));
232 return Either.left(true);
238 * Update GroupDefinition metadata
242 * @param componentType
243 * @param updatedGroup
244 * @param inTransaction
247 public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) {
249 Either<GroupDefinition, ResponseFormat> result = null;
250 boolean failed = false;
252 // Validate user exist
253 validateUserExists(user.getUserId());
254 // Validate component exist
255 org.openecomp.sdc.be.model.Component component = validateComponentExists(componentId, componentType, null);
256 // validate we can work on component
257 validateCanWorkOnComponent(component, user.getUserId());
258 List<GroupDefinition> currentGroups = component.getGroups();
259 if (CollectionUtils.isEmpty(currentGroups)) {
260 log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
261 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
264 // Validate groups exists in the component
265 Optional<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny();
266 if (!currentGroupOpt.isPresent()) {
267 log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
268 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
271 GroupDefinition currentGroup = currentGroupOpt.get();
273 lockComponent(componentId, component, "Update GroupDefinition Metadata");
275 // Validate group type is vfModule
276 if (currentGroup.getType().equals(Constants.GROUP_TOSCA_HEAT)) {
277 log.error("Failed to update the metadata of group {}. Group type is {} and cannot be updated", currentGroup.getName(), currentGroup.getType());
278 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, updatedGroup.getType());
279 result = Either.right(responseFormat);
282 result = updateGroupMetadata(component, currentGroup, updatedGroup);
285 }catch (ComponentException e){
290 janusGraphDao.commit();
292 janusGraphDao.rollback();
295 graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
300 private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) {
301 String currentGroupName = currentGroup.getName();
302 Either<GroupDefinition, ResponseFormat> result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup);
304 if (result.isRight()) {
305 log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
307 if (result.isLeft()) {
308 result = updateGroup(component, currentGroup, currentGroupName);
313 private Either<GroupDefinition, ResponseFormat> updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) {
314 Either<GroupDefinition, StorageOperationStatus> handleGroupRes;
315 Either<GroupDefinition, ResponseFormat> result = null;
316 handleGroupRes = groupsOperation.updateGroup(component, updatedGroup);
317 if (handleGroupRes.isRight()) {
318 log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
319 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value())));
321 if (result == null) {
322 result = Either.left(updatedGroup);
328 * Validate and update GroupDefinition metadata
330 * @param currentGroup
334 private Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
335 // Check if to update, and update GroupDefinition name.
336 Either<Boolean, ResponseFormat> response = validateAndUpdateGroupName(currentGroup, groupUpdate);
337 if (response.isRight()) {
338 ResponseFormat errorResponse = response.right().value();
339 return Either.right(errorResponse);
342 // Do not allow to update GroupDefinition version directly.
343 String versionUpdated = groupUpdate.getVersion();
344 String versionCurrent = currentGroup.getVersion();
345 if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
346 log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
349 return Either.left(currentGroup);
353 * Validate and update GroupDefinition name
355 * @param currentGroup
359 private Either<Boolean, ResponseFormat> validateAndUpdateGroupName(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
360 String nameUpdated = groupUpdate.getName();
361 String nameCurrent = currentGroup.getName();
362 if (!nameCurrent.equals(nameUpdated)) {
363 Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true);
364 if (validatNameResponse.isRight()) {
365 ResponseFormat errorRespons = validatNameResponse.right().value();
366 return Either.right(errorRespons);
368 currentGroup.setName(groupUpdate.getName());
370 return Either.left(true);
374 * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name: MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part
375 * MyDesc was changed.
377 * @param currentGroupName
378 * @param groupUpdateName
381 private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) {
383 // Check if the group name is in old format.
384 if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) {
385 log.error("Group name {} is in old format", groupUpdateName);
386 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName));
389 // Check that name pats 1 and 3 did not changed (only the second
390 // part can be changed)
391 // But verify before that the current group format is the new one
392 if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) {
393 String[] split1 = currentGroupName.split(GROUP_DELIMITER_REGEX);
394 String currentResourceName = split1[0];
395 String currentCounter = split1[2];
397 String[] split2 = groupUpdateName.split(GROUP_DELIMITER_REGEX);
398 String groupUpdateResourceName = split2[0];
399 String groupUpdateCounter = split2[2];
400 if (!isforceNameModification){ //if not forced ,allow name prefix&suffix validation [no changes]
401 if (!currentResourceName.equals(groupUpdateResourceName)) {
402 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
405 if (!currentCounter.equals(groupUpdateCounter)) {
406 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
412 return Either.left(true);
413 } catch (Exception e) {
414 log.error("Error valiadting group name", e);
415 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
421 * associate artifacts to a given group
425 * @param componentType
426 * @param inTransaction
429 public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) {
431 Either<GroupDefinitionInfo, ResponseFormat> result = null;
433 // Validate user exist
434 validateUserExists(userId);
435 // Validate component exist
436 org.openecomp.sdc.be.model.Component component = null;
439 ComponentParametersView componentParametersView = new ComponentParametersView();
440 componentParametersView.disableAll();
441 componentParametersView.setIgnoreGroups(false);
442 componentParametersView.setIgnoreArtifacts(false);
443 componentParametersView.setIgnoreUsers(false);
445 component = validateComponentExists(componentId, componentType, componentParametersView);
447 Either<GroupDefinition, StorageOperationStatus> groupEither = findGroupOnComponent(component, groupId);
449 if (groupEither.isRight()) {
450 log.debug("Failed to find group {} under component {}", groupId, component.getUniqueId());
451 BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO);
452 String componentTypeForResponse = getComponentTypeForResponse(component);
453 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse));
456 GroupDefinition group = groupEither.left().value();
458 List<GroupProperty> props = group.convertToGroupProperties();
459 Boolean isBase = isBaseProp(component, props);
461 List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
462 List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
463 List<String> artifactsIds = group.getArtifacts();
465 Map<String, ArtifactDefinition> deploymentArtifacts = null;
466 if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
467 deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, a -> a));
470 if (artifactsIds != null && !artifactsIds.isEmpty()) {
471 for (String id : artifactsIds) {
472 if (deploymentArtifacts == null || !deploymentArtifacts.containsKey(id)) {
473 log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND);
474 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND));
475 result = Either.right(responseFormat);
478 artifactsFromComponent.add(deploymentArtifacts.get(id));
480 addArtifactsToList(artifacts, artifactsFromComponent);
483 GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
484 resultInfo.setIsBase(isBase);
485 if (!artifacts.isEmpty()) {
486 resultInfo.setArtifacts(artifacts);
488 result = Either.left(resultInfo);
493 closeTransaction(inTransaction, result);
498 private void addArtifactsToList(List<ArtifactDefinitionInfo> artifacts, List<ArtifactDefinition> artifactsFromComponent) {
499 artifactsFromComponent.forEach(a-> artifacts.add(new ArtifactDefinitionInfo(a)));
502 private Boolean isBaseProp(Component component, List<GroupProperty> props) {
503 Boolean isBase = null;
504 if (CollectionUtils.isNotEmpty(props)) {
505 Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
506 if (isBasePropOp.isPresent()) {
507 GroupProperty propIsBase = isBasePropOp.get();
508 isBase = Boolean.parseBoolean(propIsBase.getValue());
511 BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
517 private Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) {
519 Either<GroupDefinition, StorageOperationStatus> result = null;
520 if (CollectionUtils.isNotEmpty(component.getGroups())) {
521 Optional<GroupDefinition> foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst();
522 if (foundGroup.isPresent()) {
523 result = Either.left(foundGroup.get());
526 if (result == null) {
527 result = Either.right(StorageOperationStatus.NOT_FOUND);
532 public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) {
533 Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true);
534 Collections.sort(allGroups, ArtifactTemplateInfo::compareByGroupName);
535 for (ArtifactTemplateInfo group : allGroups) {
536 Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++);
537 if (validateGenerateGroupNameRes.isRight()) {
538 validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value());
541 group.setGroupName(validateGenerateGroupNameRes.left().value());
543 return validateGenerateGroupNamesRes;
547 * Generate module name from resourceName, description and counter
549 * @param resourceSystemName
551 * @param groupCounter
554 private Either<String, ResponseFormat> validateGenerateVfModuleGroupName(String resourceSystemName, String description, int groupCounter) {
555 Either<String, ResponseFormat> validateGenerateGroupNameRes;
556 if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) {
557 final String fileName = description.replaceAll(GROUP_DELIMITER_REGEX, "\\.");
558 validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter));
560 validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME));
562 return validateGenerateGroupNameRes;
565 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) {
567 Map<String, GroupDefinition> updatedNamesGroups = new HashMap<>();
568 Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(updatedNamesGroups);
569 for (Entry<String, GroupDefinition> groupEntry : groups.entrySet()) {
570 GroupDefinition curGroup = groupEntry.getValue();
571 String groupType = curGroup.getType();
572 String groupName = groupEntry.getKey();
575 Either<String, ResponseFormat> newGroupNameRes;
576 if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) {
578 if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) {
579 counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]);
580 description = curGroup.getDescription();
582 counter = getNextVfModuleNameCounter(updatedNamesGroups);
583 description = groupName;
585 newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter);
586 if (newGroupNameRes.isRight()) {
587 log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
588 loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML.getName(),StatusCode.ERROR.name(),"Failed to generate new vf module group name. Status is: "+newGroupNameRes.right().value());
589 result = Either.right(newGroupNameRes.right().value());
592 groupName = newGroupNameRes.left().value();
593 curGroup.setName(groupName);
595 updatedNamesGroups.put(groupName, curGroup);
600 public int getNextVfModuleNameCounter(Map<String, GroupDefinition> groups) {
602 if (groups != null && !groups.isEmpty()) {
603 counter = getNextVfModuleNameCounter(groups.values());
608 public int getNextVfModuleNameCounter(Collection<GroupDefinition> groups) {
610 if (groups != null && !groups.isEmpty()) {
611 List<Integer> counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches())
612 .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(toList());
613 counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max(Integer::compare).get() + 1;
618 public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component) {
619 List<GroupDefinition> updatedGroups = new ArrayList<>();
620 Either<List<GroupDefinition>, ResponseFormat> result;
622 for (GroupDefinition group : groups) {
623 String groupType = group.getType();
624 String oldGroupName = group.getName();
626 Either<String, ResponseFormat> newGroupNameRes;
628 if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) {
629 counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]);
630 newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter);
631 if (newGroupNameRes.isRight()) {
632 log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
633 result = Either.right(newGroupNameRes.right().value());
636 newGroupName = newGroupNameRes.left().value();
637 group.setName(newGroupName);
640 updatedGroups.add(group);
644 result = Either.left(updatedGroups);
649 public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) {
650 Either<GroupDefinitionInfo, ResponseFormat> result = null;
652 // Validate user exist
653 validateUserExists(userId);
654 // Validate component exist
655 org.openecomp.sdc.be.model.Component component;
658 ComponentParametersView componentParametersView = new ComponentParametersView();
659 componentParametersView.disableAll();
660 componentParametersView.setIgnoreUsers(false);
661 componentParametersView.setIgnoreComponentInstances(false);
662 componentParametersView.setIgnoreArtifacts(false);
664 component = validateComponentExists(componentId, componentType, componentParametersView);
665 Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId);
667 if (findComponentInstanceAndGroupInstanceRes.isRight()) {
668 log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value());
669 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value()));
670 result = Either.right(responseFormat);
674 GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight();
676 Boolean isBase = isBaseProperty(component, group);
678 List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
679 List<String> artifactsIds = group.getArtifacts();
680 if (artifactsIds != null && !artifactsIds.isEmpty()) {
682 List<ComponentInstance> instances = component.getComponentInstances();
683 if (instances != null) {
684 instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId))
686 .ifPresent(f->getFirstComponentInstance(group, artifacts, artifactsIds, f));
689 GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
690 resultInfo.setIsBase(isBase);
691 if (!artifacts.isEmpty()) {
692 resultInfo.setArtifacts(artifacts);
694 result = Either.left(resultInfo);
699 closeTransaction(inTransaction, result);
703 private void getFirstComponentInstance(GroupInstance group, List<ArtifactDefinitionInfo> artifacts, List<String> artifactsIds, ComponentInstance ci) {
704 Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
705 artifactsIds.forEach(id -> deploymentArtifacts.values().stream()
706 .filter(a -> a.getUniqueId().equals(id))
708 .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
710 List<String> instArtifactsIds = group.getGroupInstanceArtifacts();
711 instArtifactsIds.forEach(id -> deploymentArtifacts.values()
713 .filter(a -> a.getUniqueId().equals(id))
715 .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
718 private Boolean isBaseProperty(Component component, GroupInstance group) {
720 Boolean isBase = null;
721 List<? extends GroupProperty> props = group.convertToGroupInstancesProperties();
722 if (props != null && !props.isEmpty()) {
723 Optional<? extends GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
724 if (isBasePropOp.isPresent()) {
725 GroupProperty propIsBase = isBasePropOp.get();
726 isBase = Boolean.parseBoolean(propIsBase.getValue());
729 BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
735 private void closeTransaction(boolean inTransaction, Either<GroupDefinitionInfo, ResponseFormat> result) {
736 if (!inTransaction) {
737 if (result == null || result.isRight()) {
738 log.debug("Going to execute rollback on create group.");
739 janusGraphDao.rollback();
741 log.debug("Going to execute commit on create group.");
742 janusGraphDao.commit();
747 private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) {
749 Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> result = null;
750 if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
751 Optional<GroupInstance> foundGroup;
752 Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst();
753 if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) {
754 foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst();
755 if (foundGroup.isPresent()) {
756 result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get()));
760 if (result == null) {
761 result = Either.right(StorageOperationStatus.NOT_FOUND);
766 private Boolean validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) {
768 for (Entry<PropertyNames, String> entry : newValues.entrySet()) {
769 PropertyNames currPropertyName = entry.getKey();
770 if (currPropertyName == PropertyNames.MIN_INSTANCES) {
771 String minValue = parentValues.get(PropertyNames.MIN_INSTANCES);
772 String maxValue = getMaxValue(newValues, currValues);
773 validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
774 new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
775 } else if (currPropertyName == PropertyNames.INITIAL_COUNT) {
776 String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES);
777 String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES);
778 validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
779 new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
780 } else if (currPropertyName == PropertyNames.MAX_INSTANCES) {
781 String minValue = getMinValue(newValues, currValues);
782 String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES);
783 validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
784 new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
790 private String getMaxValue(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues) {
791 return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
794 private String getMinValue(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues) {
795 return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
798 private Boolean validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) {
799 final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}.";
800 int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey());
801 int minInt = parseIntValue(min.getValue(), min.getKey());
802 int maxInt = parseIntValue(max.getValue(), max.getKey());
803 if (newValueInt < 0 || minInt < 0 || maxInt < 0) {
804 throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY);
805 } else if (newValueInt < minInt || newValueInt > maxInt) {
806 log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue());
807 throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(),
808 maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue());
813 private int parseIntValue(String value, PropertyNames propertyName) {
815 if (propertyName == PropertyNames.MAX_INSTANCES) {
816 result = convertIfUnboundMax(value);
817 } else if (NumberUtils.isNumber(value)) {
818 result = Integer.parseInt(value);
826 * validates received new property values and updates group instance in case of success
828 * @param oldGroupInstance
829 * @param newProperties
832 public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
834 Either<GroupInstance, ResponseFormat> actionResult = null;
835 Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null;
836 List<GroupInstanceProperty> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties);
837 if (actionResult == null) {
838 List<GroupInstanceProperty> validatedReducedNewProperties = validateRes;
839 updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties);
840 if (updateGroupInstanceResult.isRight()) {
841 log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
842 actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value())));
845 if (actionResult == null) {
846 actionResult = Either.left(updateGroupInstanceResult.left().value());
851 private List<GroupInstanceProperty> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
853 Boolean validationRes = null;
854 List<GroupInstanceProperty> actionResult = null;
855 Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
856 Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class);
857 List<GroupInstanceProperty> reducedProperties = new ArrayList<>();
858 String currPropertyName;
860 for (GroupInstanceProperty currNewProperty : newProperties) {
861 currPropertyName = currNewProperty.getName();
862 validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName));
864 if (validationRes == null || validationRes) {
865 Map<PropertyNames, String> existingPropertyValues = new EnumMap<>(PropertyNames.class);
866 Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class);
867 fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues);
868 validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues);
871 actionResult = reducedProperties;
873 } catch (Exception e) {
874 log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e);
875 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
880 private void fillValuesAndParentValuesFromExistingProperties(Map<String, GroupInstanceProperty> existingProperties, Map<PropertyNames, String> propertyValues, Map<PropertyNames, String> parentPropertyValues) {
881 PropertyNames[] allPropertyNames = PropertyNames.values();
882 for (PropertyNames name : allPropertyNames) {
883 if (isUpdatable(name)) {
884 propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue()));
885 parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue()));
890 private Boolean handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
892 Boolean validationRes = null;
893 String currPropertyName = currNewProperty.getName();
894 PropertyNames propertyName = PropertyNames.findName(currPropertyName);
896 if (currExistingProperty == null) {
897 log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName);
898 } else if (isUpdatable(propertyName)) {
899 validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty);
900 addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty);
902 validateImmutableProperty(currExistingProperty, currNewProperty);
904 if (validationRes == null) {
905 validationRes = true;
907 } catch (Exception e) {
908 log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e);
910 return validationRes;
913 private boolean isUpdatable(PropertyNames updatablePropertyName) {
914 return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber();
917 private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
919 String newValue = newProperty.getValue();
920 if (!newValue.equals(String.valueOf(existingProperty.getValue()))) {
921 newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid());
922 reducedProperties.add(newProperty);
924 if (!isEmptyMinInitialCountValue(propertyName, newValue)) {
925 newPropertyValues.put(propertyName, newValue);
929 private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) {
930 boolean result = false;
931 if ((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)) {
937 private int convertIfUnboundMax(String value) {
940 if (!NumberUtils.isNumber(value)) {
941 result = Integer.MAX_VALUE;
943 result = Integer.parseInt(value);
948 private Boolean validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
950 String parentValue = existingProperty.getParentValue();
952 newProperty.setParentValue(parentValue);
953 if (StringUtils.isEmpty(newProperty.getValue())) {
954 newProperty.setValue(parentValue);
956 if (StringUtils.isEmpty(existingProperty.getValue())) {
957 existingProperty.setValue(parentValue);
959 StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty);
960 if (status != StorageOperationStatus.OK) {
961 log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status);
962 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
967 private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) {
968 if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) {
969 log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ", oldProperty.getName(), newProperty.getValue());
973 @LockingTransactional
974 public GroupDefinition createGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupType,
977 Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, CREATE_GROUP);
979 validateGroupTypePerComponent(groupType, component);
981 GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false)
983 .on(se -> onGroupTypeNotFound(component));
985 boolean hasExistingGroups = CollectionUtils.isNotEmpty(component.getGroups());
986 GroupDefinition groupDefinition = new GroupDefinition();
987 groupDefinition.setType(groupType);
989 //find next valid counter
991 if (hasExistingGroups) {
992 nextCounter = getNewGroupCounter(component);
994 String name = TopologyTemplateOperation.buildSubComponentName(component.getName(), groupType, nextCounter);
995 groupDefinition.setName(name);
996 groupDefinition.setDescription(groupTypeDefinition.getDescription());
997 groupDefinition.setInvariantName(name);
998 groupDefinition.setCreatedFrom(CreatedFrom.UI);
1000 //Add default type properties
1001 List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
1002 List<GroupProperty> properties = groupTypeProperties.stream()
1003 .map(GroupProperty::new)
1005 groupDefinition.convertFromGroupProperties(properties);
1007 groupDefinition.convertCapabilityDefinitions(groupTypeDefinition.getCapabilities());
1009 List<GroupDefinition> gdList;
1010 if (toscaOperationFacade.canAddGroups(componentId)) {
1011 gdList = addGroups(component, Arrays.asList(groupDefinition), false)
1013 .on(this::onFailedGroupDBOperation);
1015 //createGroups also creates an edge and vertex to store group data
1016 gdList = createGroups(component, Arrays.asList(groupDefinition), false)
1018 .on(this::onFailedGroupDBOperation);
1020 return gdList.get(0);
1023 private void validateGroupTypePerComponent(String groupType, Component component) {
1024 String specificType = component.getComponentMetadataDefinition().getMetadataDataDefinition().getActualComponentType();
1025 if (!component.isTopologyTemplate()) {
1026 throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType,
1029 Map<String, Set<String>> excludedGroupTypesMap = ConfigurationManager.getConfigurationManager().getConfiguration()
1030 .getExcludedGroupTypesMapping();
1032 if (MapUtils.isNotEmpty(excludedGroupTypesMap) && StringUtils.isNotEmpty(specificType)) {
1033 Set<String> excludedGroupTypesPerComponent = excludedGroupTypesMap.get(specificType);
1034 if (excludedGroupTypesPerComponent!=null && excludedGroupTypesPerComponent.contains(groupType)) {
1035 throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType);
1040 private int getNewGroupCounter(Component component) {
1041 List<String> existingNames = component.getGroups()
1043 .map(GroupDataDefinition::getInvariantName)
1045 List<String> existingIds = component.getGroups()
1047 .map(GroupDataDefinition::getUniqueId)
1049 existingIds.addAll(existingNames);
1051 return Utils.getNextCounter(existingIds);
1054 @LockingTransactional
1055 public GroupDefinition updateGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId,
1056 String userId, GroupDefinition updatedGroup) {
1057 Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, UPDATE_GROUP);
1059 GroupDefinition existingGroup = findGroupOnComponent(component, groupId)
1061 .on(se -> onGroupNotFoundInComponentError(component, groupId));
1063 String existingGroupName = existingGroup.getName();
1064 String updatedGroupName = updatedGroup.getName();
1065 assertNewNameIsValidAndUnique(existingGroupName, updatedGroupName, component);
1066 existingGroup.setName(updatedGroupName);
1068 return updateGroup(component, existingGroup, existingGroupName)
1070 .on(this::onFailedUpdateGroupDBOperation);
1073 private void assertNewNameIsValidAndUnique(String currentGroupName, String updatedGroupName, Component component) {
1074 if (!ValidationUtils.validateResourceInstanceNameLength(updatedGroupName)) {
1075 throw new ByActionStatusComponentException(ActionStatus.EXCEEDS_LIMIT, "Group Name", ValidationUtils.RSI_NAME_MAX_LENGTH.toString());
1077 if (!ValidationUtils.validateResourceInstanceName(updatedGroupName)) {
1078 throw new ByActionStatusComponentException(ActionStatus.INVALID_VF_MODULE_NAME, updatedGroupName);
1080 if (!ComponentValidations.validateNameIsUniqueInComponent(currentGroupName, updatedGroupName, component)) {
1081 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, "Group", updatedGroupName);
1085 @LockingTransactional
1086 public GroupDefinition deleteGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId,
1088 Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, DELETE_GROUP);
1090 GroupDefinition groupDefinition = findGroupOnComponent(component, groupId)
1092 .on(se -> onGroupNotFoundInComponentError(component, groupId));
1094 List<GroupDefinition> gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition))
1096 .on(this::onFailedGroupDBOperation);
1098 updatePolicyTargetReferencingDeletedGroup(groupId, component);
1099 return gdList.get(0);
1102 private List<GroupDefinition> onFailedGroupDBOperation(ResponseFormat responseFormat) {
1103 janusGraphDao.rollback();
1104 throw new ByResponseFormatComponentException(responseFormat);
1107 private GroupDefinition onFailedUpdateGroupDBOperation(ResponseFormat responseFormat) {
1108 janusGraphDao.rollback();
1109 throw new ByResponseFormatComponentException(responseFormat);
1112 private GroupDefinition onGroupNotFoundInComponentError(Component component, String groupId) {
1113 throw new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, groupId,
1114 component.getSystemName(), getComponentTypeForResponse(component));
1117 private GroupTypeDefinition onGroupTypeNotFound(Component component) {
1118 throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_IS_INVALID, component.getSystemName(),
1119 component.getComponentType().toString());
1122 private void updatePolicyTargetReferencingDeletedGroup(String groupId, Component component) {
1123 log.debug("#updatePolicyTargetReferencingDeletedGroup - removing all component {} policy targets referencing group {}", component.getUniqueId(), groupId);
1124 ActionStatus actionStatus = policyTargetsUpdateHandler.removePoliciesTargets(component, groupId, PolicyTargetType.GROUPS);
1125 if (ActionStatus.OK != actionStatus) {
1126 janusGraphDao.rollback();
1127 throw new ByActionStatusComponentException(actionStatus, groupId);
1132 public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
1134 Map<String, GroupDataDefinition> groups = new HashMap<>();
1135 Either<List<GroupDefinition>, ResponseFormat> result = null;
1136 Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
1137 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
1138 if (allDataTypes.isRight()) {
1139 JanusGraphOperationStatus status = allDataTypes.right().value();
1140 BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
1141 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1145 // handle groups and convert to tosca data
1146 if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
1147 for (GroupDefinition groupDefinition : groupDefinitions) {
1148 Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, groupDefinition, allDataTypes.left().value());
1149 if (handleGroupRes.isRight()) {
1150 result = Either.right(handleGroupRes.right().value());
1153 GroupDefinition handledGroup = handleGroupRes.left().value();
1154 groups.put(handledGroup.getInvariantName(), new GroupDataDefinition(handledGroup));
1158 if (result == null) {
1159 createGroupsResult = groupsOperation.createGroups(component, groups);
1160 if (createGroupsResult.isRight()) {
1161 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
1164 if (result == null) {
1165 addCalculatedCapabilitiesWithPropertiesToComponent(component, groupDefinitions, fromCsar);
1167 if (result == null) {
1168 result = Either.left(groupDefinitions);
1170 component.setGroups(groupDefinitions);
1174 private void updateCalculatedCapabilitiesWithPropertiesOnComponent(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
1175 groupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields);
1176 StorageOperationStatus status = groupsOperation.updateCalculatedCapabilitiesWithProperties(component.getUniqueId(),
1177 extractCapabilitiesFromGroups(groupDefinitions), extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar));
1178 if(status != StorageOperationStatus.OK){
1179 log.error("#updateCalculatedCapabilitiesWithPropertiesOnComponent - failed to update the groups' calculated capabilities with the properties on the component {}. ", component.getUniqueId());
1180 rollbackWithException(componentsUtils.convertFromStorageResponse(status));
1184 private void addCalculatedCapabilitiesWithPropertiesToComponent(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
1185 groupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields);
1186 StorageOperationStatus status = groupsOperation.addCalculatedCapabilitiesWithProperties(component.getUniqueId(),
1187 extractCapabilitiesFromGroups(groupDefinitions), extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar));
1188 if(status != StorageOperationStatus.OK){
1189 log.error("#addCalculatedCapabilitiesWithPropertiesToComponent - failed to add the groups' calculated capabilities with the properties to the component {}. ", component.getUniqueId());
1190 rollbackWithException(componentsUtils.convertFromStorageResponse(status));
1194 private void deleteCalculatedCapabilitiesWithPropertiesFromComponent(Component component, final List<GroupDefinition> groupDefinitions) {
1195 StorageOperationStatus status = groupsOperation.deleteCalculatedCapabilitiesWithProperties(component.getUniqueId(), groupDefinitions);
1196 if(status != StorageOperationStatus.OK){
1197 log.error("#deleteCalculatedCapabilitiesWithPropertiesFromComponent - failed to remove the groups' calculated capabilities with the properties from the component {}. ", component.getUniqueId());
1198 rollbackWithException(componentsUtils.convertFromStorageResponse(status));
1202 public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
1204 Either<List<GroupDefinition>, ResponseFormat> result = null;
1205 Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
1206 List<GroupDataDefinition> groups = new ArrayList<>();
1208 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
1209 if (allDataTypes.isRight()) {
1210 JanusGraphOperationStatus status = allDataTypes.right().value();
1211 BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
1212 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1216 // handle groups and convert to tosca data
1217 if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
1218 for (GroupDefinition groupDefinition : groupDefinitions) {
1219 Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, groupDefinition, allDataTypes.left().value());
1220 if (handleGroupRes.isRight()) {
1221 result = Either.right(handleGroupRes.right().value());
1224 GroupDefinition handledGroup = handleGroupRes.left().value();
1225 groups.add(new GroupDataDefinition(handledGroup));
1228 if (result == null) {
1229 createGroupsResult = groupsOperation.addGroups(component, groups);
1230 if (createGroupsResult.isRight()) {
1231 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
1233 component.addGroups(createGroupsResult.left().value());
1235 if (result == null) {
1236 addCalculatedCapabilitiesWithPropertiesToComponent(component, groupDefinitions, fromCsar);
1238 if (result == null) {
1239 result = Either.left(groupDefinitions);
1244 public Either<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, List<GroupDefinition> groupDefinitions) {
1246 Either<List<GroupDefinition>, StorageOperationStatus> deleteGroupsResult;
1248 deleteGroupsResult = groupsOperation.deleteGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()));
1249 if (deleteGroupsResult.isRight()) {
1250 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteGroupsResult.right().value())));
1252 deleteCalculatedCapabilitiesWithPropertiesFromComponent(component, groupDefinitions);
1254 if (component.getGroups()!=null) {
1255 component.getGroups().removeAll(deleteGroupsResult.left().value());
1257 return Either.left(deleteGroupsResult.left().value());
1261 * Update specific group version
1262 * @param fromCsar TODO
1265 public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, List<GroupDefinition> groupDefinitions, boolean fromCsar) {
1267 Either<List<GroupDefinition>, ResponseFormat> result = null;
1268 Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult;
1270 createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), PromoteVersionEnum.MINOR);
1271 if (createGroupsResult.isRight()) {
1272 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
1274 if (result == null) {
1275 updateCalculatedCapabilitiesWithPropertiesOnComponent(component, groupDefinitions, fromCsar);
1277 if (result == null) {
1278 result = Either.left(groupDefinitions);
1283 private Either<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
1285 log.trace("Going to create group {}", groupDefinition);
1286 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(),StatusCode.STARTED,"Start to create group: {}",groupDefinition.getName()+ " for component " + component.getName());
1287 // 3. verify group not already exist
1288 String groupDefinitionName = groupDefinition.getName();
1289 if (groupExistsInComponent(groupDefinitionName, component)) {
1290 String componentTypeForResponse = getComponentTypeForResponse(component);
1291 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinitionName, component.getNormalizedName(), componentTypeForResponse));
1293 // 4. verify type of group exist
1294 String groupType = groupDefinition.getType();
1295 if (StringUtils.isEmpty(groupType)) {
1296 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinitionName));
1298 Either<GroupTypeDefinition, StorageOperationStatus> getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
1299 if (getGroupType.isRight()) {
1300 StorageOperationStatus status = getGroupType.right().value();
1301 if (status == StorageOperationStatus.NOT_FOUND) {
1302 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} cannot be found",groupDefinition.getName());
1303 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO);
1304 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
1306 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1309 // 6. verify the component instances type are allowed according to
1310 // the member types in the group type
1311 GroupTypeDefinition groupTypeDefinition = getGroupType.left().value();
1313 Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, groupDefinitionName, groupDefinition.getMembers(), groupTypeDefinition.getMembers());
1315 if (areValidMembers.isRight()) {
1316 ResponseFormat responseFormat = areValidMembers.right().value();
1317 return Either.right(responseFormat);
1319 // 7. verify the artifacts belongs to the component
1320 Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP);
1321 if (areValidArtifacts.isRight()) {
1322 ResponseFormat responseFormat = areValidArtifacts.right().value();
1323 return Either.right(responseFormat);
1325 List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
1327 List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
1328 List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>();
1329 if (CollectionUtils.isNotEmpty(properties)) {
1330 if (CollectionUtils.isEmpty(groupTypeProperties)) {
1331 BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO);
1332 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} does not have properties ",groupDefinition.getName());
1333 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.MATCH_NOT_FOUND))));
1336 Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(PropertyDefinition::getName, p -> p));
1338 Either<GroupProperty, JanusGraphOperationStatus> addPropertyResult;
1340 for (GroupProperty prop : properties) {
1341 addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes, groupType);
1342 if (addPropertyResult.isRight()) {
1343 BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO);
1344 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertyResult.right().value()))));
1346 updatedGroupTypeProperties.add(addPropertyResult.left().value());
1352 if (groupDefinition.getUniqueId() == null) {
1353 String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinitionName);
1354 groupDefinition.setUniqueId(uid);
1356 groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties);
1357 groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1358 groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID());
1359 groupDefinition.setVersion(INITIAL_VERSION);
1360 groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
1361 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"group {} has been created ",groupDefinition.getName());
1362 return Either.left(groupDefinition);
1365 private static boolean groupExistsInComponent(String groupDefinitionName, Component component) {
1366 boolean found = false;
1367 List<GroupDefinition> groups = component.getGroups();
1368 if (CollectionUtils.isNotEmpty(groups)) {
1369 found = groups.stream().filter(p -> (p.getName().equalsIgnoreCase(groupDefinitionName))
1370 || p.getInvariantName().equalsIgnoreCase(groupDefinitionName))
1371 .findFirst().orElse(null) != null;
1376 private Either<GroupProperty, JanusGraphOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes, String groupType) {
1379 return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT);
1382 String propertyType = prop.getType();
1383 String value = groupProperty.getValue();
1385 Either<String, JanusGraphOperationStatus> checkInnerType = propertyOperation.checkInnerType(prop);
1386 if (checkInnerType.isRight()) {
1387 JanusGraphOperationStatus status = checkInnerType.right().value();
1388 return Either.right(status);
1391 String innerType = checkInnerType.left().value();
1393 log.debug("Before validateAndUpdatePropertyValue");
1394 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes);
1395 log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
1397 String newValue = value;
1398 if (isValid.isRight()) {
1399 Boolean res = isValid.right().value();
1401 return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT);
1404 Object object = isValid.left().value();
1405 if (object != null) {
1406 newValue = object.toString();
1410 String uniqueId = shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index)
1411 : prop.getUniqueId();
1413 groupProperty.setUniqueId(uniqueId);
1414 groupProperty.setValue(newValue);
1415 groupProperty.setType(prop.getType());
1416 groupProperty.setDefaultValue(prop.getDefaultValue());
1417 groupProperty.setDescription(prop.getDescription());
1418 groupProperty.setSchema(prop.getSchema());
1419 groupProperty.setPassword(prop.isPassword());
1420 groupProperty.setParentUniqueId(prop.getUniqueId());
1422 log.debug("Before adding property value to graph {}", groupProperty);
1424 return Either.left(groupProperty);
1427 // For old groups we want to leave indexing of property
1428 // For new groups we just need the types
1429 private boolean shouldReconstructUniqueId(String groupType) {
1430 return Constants.GROUP_TOSCA_HEAT.equals(groupType) || Constants.DEFAULT_GROUP_VF_MODULE.equals(groupType);