1 package org.openecomp.sdc.be.components.impl;
3 import static java.util.stream.Collectors.toMap;
4 import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent;
5 import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter;
6 import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields;
10 import java.util.function.Function;
12 import org.apache.commons.collections.CollectionUtils;
13 import org.apache.commons.lang3.StringUtils;
14 import org.openecomp.sdc.be.dao.api.ActionStatus;
15 import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
16 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
17 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
18 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
19 import org.openecomp.sdc.be.model.Component;
20 import org.openecomp.sdc.be.model.ComponentParametersView;
21 import org.openecomp.sdc.be.model.PolicyDefinition;
22 import org.openecomp.sdc.be.model.PolicyTypeDefinition;
23 import org.openecomp.sdc.be.model.Resource;
24 import org.openecomp.sdc.be.model.User;
25 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
26 import org.openecomp.sdc.common.datastructure.Wrapper;
27 import org.openecomp.sdc.exception.ResponseFormat;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
31 import fj.data.Either;
34 * Provides specified business logic to create, retrieve, update, delete a policy
36 @org.springframework.stereotype.Component("policyBusinessLogic")
37 public class PolicyBusinessLogic extends BaseBusinessLogic {
39 private static final String FAILED_TO_VALIDATE_COMPONENT = "#{} - failed to validate the component {} before policy processing. ";
40 private static final Logger log = LoggerFactory.getLogger(PolicyBusinessLogic.class);
43 * Adds the newly created policy of the specified type to the component
45 * @param componentType the type of the component
46 * @param componentId the id of the component which the policy resides under
47 * @param policyTypeName the name of the policy type
48 * @param userId the user creator id
49 * @param shouldLock the flag defining if the component should be locked
50 * @return a policy or an error in a response format
53 public Either<PolicyDefinition, ResponseFormat> createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) {
55 Either<PolicyDefinition, ResponseFormat> result = null;
56 log.trace("#createPolicy - starting to create policy of the type {} on the component {}. ", policyTypeName, componentId);
57 Wrapper<Component> component = new Wrapper<>();
59 result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock)
62 component.setInnerElement(c);
63 return createPolicy(policyTypeName, c);
65 } catch (Exception e) {
66 log.error("#createPolicy - the exception occurred upon creation of a policy of the type {} for the component {}: ", policyTypeName, componentId, e);
67 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
70 unlockComponent(shouldLock, result, component);
76 * Retrieves the policy of the component by UniqueId
78 * @param componentType
84 public Either<PolicyDefinition, ResponseFormat> getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) {
85 Either<PolicyDefinition, ResponseFormat> result = null;
86 log.trace("#getPolicy - starting to retrieve the policy {} of the component {}. ", policyId, componentId);
88 result = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId)
90 .bind(c -> getPolicyById(c, policyId));
91 } catch (Exception e) {
92 log.error("#getPolicy - the exception occurred upon retrieving the policy {} of the component {}: ", policyId, componentId, e);
93 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
99 * Updates the policy of the component
101 * @param componentType the type of the component
102 * @param componentId the id of the component which the policy resides under
104 * @param userId the user modifier id
105 * @param shouldLock the flag defining if the component should be locked
106 * @return a policy or an error in a response format
108 public Either<PolicyDefinition, ResponseFormat> updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) {
109 Either<PolicyDefinition, ResponseFormat> result = null;
110 log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId);
111 Wrapper<Component> component = new Wrapper<>();
113 result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock)
116 component.setInnerElement(c);
117 return validateAndUpdatePolicy(c, policy);
119 } catch (Exception e) {
120 log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(), componentId, e);
121 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
123 unlockComponent(shouldLock, result, component);
129 * Deletes the policy from the component
131 * @param componentType the type of the component
132 * @param componentId the id of the component which the policy resides under
133 * @param policyId the id of the policy which its properties to return
134 * @param userId the user modifier id
135 * @param shouldLock the flag defining if the component should be locked
136 * @return a policy or an error in a response format
138 public Either<PolicyDefinition, ResponseFormat> deletePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) {
139 Either<PolicyDefinition, ResponseFormat> result = null;
140 log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId);
141 Wrapper<Component> component = new Wrapper<>();
143 result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock)
146 component.setInnerElement(c);
147 return deletePolicy(c, policyId);
149 } catch (Exception e) {
150 log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId, e);
152 unlockComponent(shouldLock, result, component);
157 public Either<PolicyDefinition, ResponseFormat> updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId, Map<PolicyTargetType, List<String>> targets, String userId) {
159 Either<PolicyDefinition, ResponseFormat> result = null;
160 log.debug("updating the policy id {} targets with the components {}. ", policyId, componentId);
161 Component component = null;
164 //not right error response
165 result = validateAndLockComponentAndUserBeforeWriteOperation(componentTypeEnum, componentId, userId, true)
167 .bind(cmpt -> validateAndUpdatePolicyTargets(cmpt, policyId, targets));
172 unlockComponentById(result, componentId);
178 private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicyTargets(Component component, String policyId, Map<PolicyTargetType, List<String>> targets) {
179 if (!validateTargetsExistAndTypesCorrect(component.getUniqueId(), targets)) {
180 log.debug("Error finding all the targets: {} .", targets);
181 return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, StringUtils.join(targets.values())));
183 return updateTargets(component.getUniqueId(), component.getPolicyById(policyId), targets, policyId);
187 private boolean validateTargetsExistAndTypesCorrect(String componentId, Map<PolicyTargetType, List<String>> targets) {
188 Either<Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaFullElement(componentId);
189 Component parentComponent = componentEither.left().value();
191 return targets.entrySet().stream().noneMatch(t -> checkTargetNotExistOnComponentByType(parentComponent, t));
194 private boolean checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry<PolicyTargetType, List<String>> targetEntry) {
196 return targetEntry.getValue().stream()
197 .anyMatch(id -> checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().toString()));
200 private boolean checkNotPresenceInComponentByType(Component parentComponent, String uniqueId, String type) {
201 if (type.equalsIgnoreCase(PolicyTargetType.GROUPS.getName()) && parentComponent.getGroups() != null) {
202 return !parentComponent.getGroupById(uniqueId).isPresent();
203 } else if (type.equalsIgnoreCase(PolicyTargetType.COMPONENT_INSTANCES.getName()) && parentComponent.getComponentInstances() != null) {
204 return !parentComponent.getComponentInstanceById(uniqueId).isPresent();
209 private PolicyDefinition setPolicyTargets(PolicyDefinition policyDefinition, Map<PolicyTargetType, List<String>> targets) {
210 policyDefinition.setTargets(targets);
211 return policyDefinition;
216 * @param componentType the type of the component
217 * @param componentId the id of the component which the policy resides under
218 * @param policyId the id of the policy which its properties to return
219 * @param userId the user id
220 * @return a list of policy properties or an error in a response format
222 public Either<List<PropertyDataDefinition>, ResponseFormat> getPolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, String userId) {
223 log.debug("#getPolicyProperties - fetching policy properties for component {} and policy {}", componentId, policyId);
225 return validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId)
227 .bind(cmpt -> getPolicyById(cmpt, policyId)).left().map(PolicyDataDefinition::getProperties);
234 * Updates the policy properties of the component
236 * @param componentType the type of the component
237 * @param componentId the id of the component which the policy resides under
238 * @param policyId the id of the policy which its properties to return
239 * @param properties a list of policy properties containing updated values
240 * @param userId the user modifier id
241 * @param shouldLock the flag defining if the component should be locked
242 * @return a list of policy properties or anerrorin a response format
244 public Either<List<PropertyDataDefinition>, ResponseFormat> updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, PropertyDataDefinition[] properties, String userId, boolean shouldLock) {
245 Either<List<PropertyDataDefinition>, ResponseFormat> result = null;
246 log.trace("#updatePolicyProperties - starting to update properties of the policy {} on the component {}. ", policyId, componentId);
247 Wrapper<Component> component = new Wrapper<>();
249 result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock).left().bind(c -> setComponentValidateUpdatePolicyProperties(policyId, properties, component, c));
250 } catch (Exception e) {
251 log.error("#updatePolicyProperties - the exception {} occurred upon update properties of the policy {} for the component {}: ", policyId, componentId, e);
252 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
254 if (shouldLock && !component.isEmpty()) {
255 unlockComponent(result, component.getInnerElement());
261 private Either<List<PropertyDataDefinition>, ResponseFormat> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Wrapper<Component> component, Component c) {
262 component.setInnerElement(c);
263 return validateAndUpdatePolicyProperties(c, policyId, properties)
265 .map(PolicyDefinition::getProperties);
268 private void unlockComponent(boolean shouldLock, Either<PolicyDefinition, ResponseFormat> result, Wrapper<Component> component) {
269 if (shouldLock && !component.isEmpty()) {
270 unlockComponent(result, component.getInnerElement());
274 private Either<PolicyDefinition, ResponseFormat> getPolicyById(Component component, String policyId) {
275 PolicyDefinition policyById = component.getPolicyById(policyId);
276 if (policyById == null) {
277 String cmptId = component.getUniqueId();
278 log.debug("#getPolicyById - policy with id {} does not exist on component with id {}", policyId, cmptId);
279 return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, cmptId));
281 return Either.left(policyById);
284 private Either<PolicyDefinition, ResponseFormat> createPolicy(String policyTypeName, Component component) {
285 return validatePolicyTypeOnCreatePolicy(policyTypeName, component).left().bind(type -> addPolicyToComponent(type, component));
288 private Either<PolicyDefinition, ResponseFormat> addPolicyToComponent(PolicyTypeDefinition policyType, Component component) {
289 return toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies()))
290 .either(Either::left, r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r))));
293 private Either<PolicyTypeDefinition, ResponseFormat> validatePolicyTypeOnCreatePolicy(String policyTypeName, Component component) {
294 return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName)
295 .either(l -> validatePolicyTypeNotExcluded(l, component), r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r))));
298 private Either<PolicyTypeDefinition, ResponseFormat> validatePolicyTypeNotExcluded(PolicyTypeDefinition policyType, Component component) {
299 if (getExcludedPolicyTypesByComponent(component).contains(policyType.getType())) {
300 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(), getComponentOrResourceTypeName(component)));
302 return Either.left(policyType);
305 private String getComponentOrResourceTypeName(Component component) {
306 return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name() : ((Resource) component).getResourceType().name();
309 private Either<Component, ResponseFormat> validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, boolean shouldLock) {
310 Wrapper<Component> component = new Wrapper<>();
311 return validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId)
313 .bind(this::validateComponentIsTopologyTemplate)
316 component.setInnerElement(c);
317 return validateCanWorkOnComponent(c, userId);
320 .bind(l -> lockComponent(component.getInnerElement(), shouldLock, "policyWritingOperation"))
321 .either(l -> Either.left(component.getInnerElement()), r -> {
322 log.error(FAILED_TO_VALIDATE_COMPONENT, componentId);
323 return Either.right(r);
327 private Either<Component, ResponseFormat> validateComponentIsTopologyTemplate(Component component) {
328 if (!component.isTopologyTemplate()) {
329 log.error("#validateComponentIsTopologyTemplate - policy association to a component of Tosca type {} is not allowed. ", component.getToscaType());
330 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_POLICIES, "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType()));
332 return Either.left(component);
335 private Either<Component, ResponseFormat> validateContainerComponentAndUserBeforeReadOperation(ComponentTypeEnum componentType, String componentId, String userId) {
336 Either<Component, ResponseFormat> result = null;
337 log.trace("#validateContainerComponentAndUserBeforeReadOperation - starting to validate the user {} before policy processing. ", userId);
338 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Policy", false);
339 if (resp.isRight()) {
340 log.error("#validateContainerComponentAndUserBeforeReadOperation - failed to validate the user {} before policy processing. ", userId);
341 result = Either.right(resp.right().value());
343 result = validateComponentExists(componentType, componentId);
344 if (result.isRight()) {
345 log.error(FAILED_TO_VALIDATE_COMPONENT, "#validateContainerComponentAndUserBeforeReadOperation", componentId);
352 private Either<Component, ResponseFormat> validateComponentExists(ComponentTypeEnum componentType, String componentId) {
354 ComponentParametersView filter = new ComponentParametersView(true);
355 filter.setIgnorePolicies(false);
356 filter.setIgnoreUsers(false);
357 filter.setIgnoreComponentInstances(false);
358 filter.setIgnoreGroups(false);
359 return validateComponentExists(componentId, componentType, filter);
363 private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicy(Component component, PolicyDefinition policy) {
364 return getPolicyById(component, policy.getUniqueId())
366 .bind(np -> validateUpdatePolicyBeforeUpdate(policy, np, component.getPolicies()))
368 .bind(p -> updatePolicyOfComponent(component, p));
371 private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicyProperties(Component component, String policyId, PropertyDataDefinition[] properties) {
372 return getPolicyById(component, policyId)
374 .bind(p -> validateUpdatePolicyPropertiesBeforeUpdate(p, properties))
375 .left().bind(l -> updatePolicyOfComponent(component.getUniqueId(), l));
378 private Either<PolicyDefinition, ResponseFormat> updatePolicyOfComponent(String componentId, PolicyDefinition policy) {
379 return toscaOperationFacade.updatePolicyOfComponent(componentId, policy)
381 .bind(r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r))));
384 private Either<PolicyDefinition, ResponseFormat> validateUpdatePolicyPropertiesBeforeUpdate(PolicyDefinition policy, PropertyDataDefinition[] newProperties) {
385 if (CollectionUtils.isEmpty(policy.getProperties())) {
386 log.error("#validateUpdatePolicyPropertiesBeforeUpdate - failed to update properites of the policy. Properties were not found on the policy. ");
387 return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
389 return updatePropertyValues(policy, newProperties);
392 private Either<PolicyDefinition, ResponseFormat> updatePropertyValues(PolicyDefinition policy, PropertyDataDefinition[] newProperties) {
394 Map<String, PropertyDataDefinition> oldProperties = policy.getProperties().stream().collect(toMap(PropertyDataDefinition::getName, Function.identity()));
395 for (PropertyDataDefinition newProperty : newProperties) {
396 if (!oldProperties.containsKey(newProperty.getName())) {
397 log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. ");
398 return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getName()));
400 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(newProperty, true);
401 if (newPropertyValueEither.isRight()) {
402 return Either.right(newPropertyValueEither.right().value());
404 oldProperties.get(newProperty.getName()).setValue(newPropertyValueEither.left().value());
406 return Either.left(policy);
409 private Either<PolicyDefinition, ResponseFormat> deletePolicy(Component component, String policyId) {
410 return getPolicyById(component, policyId)
412 .bind(p -> removePolicyFromComponent(component, p));
415 private Either<PolicyDefinition, ResponseFormat> updatePolicyOfComponent(Component component, PolicyDefinition policy) {
416 Either<PolicyDefinition, StorageOperationStatus> updatePolicyRes = toscaOperationFacade.updatePolicyOfComponent(component.getUniqueId(), policy);
417 if (updatePolicyRes.isRight()) {
418 log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyRes.right().value());
419 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updatePolicyRes.right().value())));
421 log.trace("#updatePolicyOfComponent - the policy with the name {} was updated. ", updatePolicyRes.left().value().getName());
422 return Either.left(updatePolicyRes.left().value());
426 private Either<PolicyDefinition, ResponseFormat> removePolicyFromComponent(Component component, PolicyDefinition policy) {
427 StorageOperationStatus updatePolicyStatus = toscaOperationFacade.removePolicyFromComponent(component.getUniqueId(), policy.getUniqueId());
428 if (updatePolicyStatus != StorageOperationStatus.OK) {
429 log.error("#removePolicyFromComponent - failed to remove policy {} from the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyStatus);
430 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updatePolicyStatus)));
432 log.trace("#removePolicyFromComponent - the policy with the name {} was deleted. ", updatePolicyStatus);
433 return Either.left(policy);
437 private Either<PolicyDefinition, ResponseFormat> validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, Map<String, PolicyDefinition> policies) {
438 return validatePolicyFields(recievedPolicy, new PolicyDefinition(oldPolicy), policies)
440 .bind(r -> Either.right(componentsUtils.getResponseFormat(r, recievedPolicy.getName())));
443 private Either<PolicyDefinition, ResponseFormat> updateTargets(String componentId, PolicyDefinition policy, Map<PolicyTargetType, List<String>> targets, String policyId) {
445 return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, componentId));
447 PolicyDefinition updatedPolicy = setPolicyTargets(policy, targets);
448 return updatePolicyOfComponent(componentId, updatedPolicy);