2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2021 Nordix Foundation.
6 * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pap.main.rest;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
29 import java.util.Objects;
31 import java.util.function.Consumer;
32 import java.util.stream.Collectors;
33 import javax.ws.rs.core.Response.Status;
34 import org.onap.policy.common.parameters.BeanValidationResult;
35 import org.onap.policy.common.parameters.ValidationResult;
36 import org.onap.policy.common.parameters.ValidationStatus;
37 import org.onap.policy.common.utils.services.Registry;
38 import org.onap.policy.models.base.PfModelException;
39 import org.onap.policy.models.pdp.concepts.Pdp;
40 import org.onap.policy.models.pdp.concepts.PdpGroup;
41 import org.onap.policy.models.pdp.concepts.PdpGroups;
42 import org.onap.policy.models.pdp.concepts.PdpStateChange;
43 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
44 import org.onap.policy.models.pdp.concepts.PdpUpdate;
45 import org.onap.policy.models.pdp.enums.PdpState;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * Provider for PAP component to create or update PDP groups. The following items must be in the
56 * <li>PDP Modification Lock</li>
57 * <li>PDP Modify Request Map</li>
58 * <li>PAP DAO Factory</li>
61 public class PdpGroupCreateOrUpdateProvider extends ProviderBase {
62 private static final Logger logger = LoggerFactory.getLogger(PdpGroupCreateOrUpdateProvider.class);
65 * Constructs the object.
67 public PdpGroupCreateOrUpdateProvider() {
72 * Creates or updates PDP groups.
74 * @param groups PDP group configurations to be created or updated
75 * @throws PfModelException if an error occurred
77 public void createOrUpdateGroups(PdpGroups groups) throws PfModelException {
78 var result = new BeanValidationResult("groups", groups);
79 groups.checkForDuplicateGroups(result);
80 if (!result.isValid()) {
81 String msg = result.getResult().trim();
83 throw new PfModelException(Status.BAD_REQUEST, msg);
85 // During PdpGroup create/update, policies are not supposed to be deployed/undeployed into the group.
86 // There is a separate API for this.
87 List<PdpSubGroup> subGroupsWithPolicies =
88 groups.getGroups().parallelStream().flatMap(group -> group.getPdpSubgroups().parallelStream())
89 .filter(subGroup -> null != subGroup.getPolicies() && !subGroup.getPolicies().isEmpty())
90 .collect(Collectors.toList());
91 if (!subGroupsWithPolicies.isEmpty()) {
93 "Policies cannot be deployed during PdpGroup Create/Update operation. Ignoring the list of policies");
94 subGroupsWithPolicies.forEach(subGroup -> subGroup.setPolicies(Collections.emptyList()));
96 process(groups, this::createOrUpdate);
100 * Creates or updates PDP groups. This is the method that does the actual work.
102 * @param data session data
103 * @param groups PDP group configurations
104 * @throws PfModelException if an error occurred
106 private void createOrUpdate(SessionData data, PdpGroups groups) throws PfModelException {
107 var result = new BeanValidationResult("groups", groups);
109 for (PdpGroup group : groups.getGroups()) {
110 PdpGroup dbgroup = data.getGroup(group.getName());
111 ValidationResult groupValidationResult;
112 if (dbgroup == null) {
114 groupValidationResult = group.validatePapRest(false);
115 if (groupValidationResult.isValid()) {
116 result.addResult(addGroup(data, group));
118 result.addResult(groupValidationResult);
123 groupValidationResult = group.validatePapRest(true);
124 if (groupValidationResult.isValid()) {
125 result.addResult(updateGroup(data, dbgroup, group));
127 result.addResult(groupValidationResult);
132 if (!result.isValid()) {
133 throw new PfModelException(Status.BAD_REQUEST, result.getResult().trim());
140 * @param data session data
141 * @param group the group to be added
142 * @return the validation result
143 * @throws PfModelException if an error occurred
145 private ValidationResult addGroup(SessionData data, PdpGroup group) throws PfModelException {
146 var result = new BeanValidationResult(group.getName(), group);
148 validateGroupOnly(group, result);
149 if (!result.isValid()) {
154 if (group.getPdpGroupState() == null) {
155 group.setPdpGroupState(PdpState.ACTIVE);
158 for (PdpSubGroup subgrp : group.getPdpSubgroups()) {
159 result.addResult(addSubGroup(data, subgrp));
162 if (result.isValid()) {
170 * Performs additional validations of a group, but does not examine the subgroups.
172 * @param group the group to be validated
173 * @param result the validation result
175 private void validateGroupOnly(PdpGroup group, BeanValidationResult result) {
176 if (group.getPdpGroupState() == null) {
180 switch (group.getPdpGroupState()) {
186 result.addResult("pdpGroupState", group.getPdpGroupState(),
187 ValidationStatus.INVALID, "must be null, ACTIVE, or PASSIVE");
193 * Updates an existing group.
195 * @param data session data
196 * @param dbgroup the group, as it appears within the DB
197 * @param group the group to be added
198 * @return the validation result
199 * @throws PfModelException if an error occurred
201 private ValidationResult updateGroup(SessionData data, PdpGroup dbgroup, PdpGroup group) throws PfModelException {
202 var result = new BeanValidationResult(group.getName(), group);
204 if (!Objects.equals(dbgroup.getProperties(), group.getProperties())) {
205 result.addResult("properties", "", ValidationStatus.INVALID, "cannot change properties");
208 boolean updated = updateField(dbgroup.getDescription(), group.getDescription(), dbgroup::setDescription);
210 updateField(dbgroup.getPdpGroupState(), group.getPdpGroupState(), dbgroup::setPdpGroupState) || updated;
211 updated = notifyPdpsDelSubGroups(data, dbgroup, group) || updated;
212 updated = addOrUpdateSubGroups(data, dbgroup, group, result) || updated;
214 if (result.isValid() && updated) {
222 * Updates a field, if the new value is different than the old value.
224 * @param oldValue old value
225 * @param newValue new value
226 * @param setter function to set the field to the new value
227 * @return {@code true} if the field was updated, {@code false} if it already matched
230 private <T> boolean updateField(T oldValue, T newValue, Consumer<T> setter) {
231 if (oldValue == newValue) {
235 if (oldValue != null && oldValue.equals(newValue)) {
239 setter.accept(newValue);
244 * Adds or updates subgroups within the group.
246 * @param data session data
247 * @param dbgroup the group, as it appears within the DB
248 * @param group the group to be added
249 * @param result the validation result
250 * @return {@code true} if the DB group was modified, {@code false} otherwise
251 * @throws PfModelException if an error occurred
253 private boolean addOrUpdateSubGroups(SessionData data, PdpGroup dbgroup, PdpGroup group,
254 BeanValidationResult result) throws PfModelException {
256 // create a map of existing subgroups
257 Map<String, PdpSubGroup> type2sub = new HashMap<>();
258 dbgroup.getPdpSubgroups().forEach(subgrp -> type2sub.put(subgrp.getPdpType(), subgrp));
262 for (PdpSubGroup subgrp : group.getPdpSubgroups()) {
263 PdpSubGroup dbsub = type2sub.get(subgrp.getPdpType());
264 var subResult = new BeanValidationResult(subgrp.getPdpType(), subgrp);
268 subResult.addResult(addSubGroup(data, subgrp));
269 dbgroup.getPdpSubgroups().add(subgrp);
272 updated = updateSubGroup(dbsub, subgrp, subResult) || updated;
275 result.addResult(subResult);
282 * Notifies any PDPs whose subgroups are being removed.
284 * @param data session data
285 * @param dbgroup the group, as it appears within the DB
286 * @param group the group being updated
287 * @return {@code true} if a subgroup was removed, {@code false} otherwise
288 * @throws PfModelException if an error occurred
290 private boolean notifyPdpsDelSubGroups(SessionData data, PdpGroup dbgroup, PdpGroup group) throws PfModelException {
293 // subgroups, as they appear within the updated group
294 Set<String> subgroups = new HashSet<>();
295 group.getPdpSubgroups().forEach(subgrp -> subgroups.add(subgrp.getPdpType()));
297 // loop through subgroups as they appear within the DB
298 for (PdpSubGroup subgrp : dbgroup.getPdpSubgroups()) {
300 if (!subgroups.contains(subgrp.getPdpType())) {
301 // this subgroup no longer appears - notify its PDPs
303 notifyPdpsDelSubGroup(data, subgrp);
304 trackPdpsDelSubGroup(data, dbgroup.getName(), subgrp);
312 * Notifies the PDPs that their subgroup is being removed.
314 * @param data session data
315 * @param subgrp subgroup that is being removed
317 private void notifyPdpsDelSubGroup(SessionData data, PdpSubGroup subgrp) {
318 for (Pdp pdp : subgrp.getPdpInstances()) {
319 String name = pdp.getInstanceId();
322 var change = new PdpStateChange();
323 change.setName(name);
324 change.setState(PdpState.PASSIVE);
326 // remove it from subgroup and undeploy all policies
327 var update = new PdpUpdate();
328 update.setName(name);
330 data.addRequests(update, change);
335 * Tracks PDP responses when their subgroup is removed.
337 * @param data session data
338 * @param pdpGroup PdpGroup name
339 * @param subgrp subgroup that is being removed
340 * @throws PfModelException if an error occurred
342 private void trackPdpsDelSubGroup(SessionData data, String pdpGroup, PdpSubGroup subgrp) throws PfModelException {
343 Set<String> pdps = subgrp.getPdpInstances().stream().map(Pdp::getInstanceId).collect(Collectors.toSet());
345 for (ToscaConceptIdentifier policyId : subgrp.getPolicies()) {
346 data.trackUndeploy(policyId, pdps, pdpGroup, subgrp.getPdpType());
351 * Adds a new subgroup.
353 * @param data session data
354 * @param subgrp the subgroup to be added, updated to fully qualified versions upon
356 * @return the validation result
357 * @throws PfModelException if an error occurred
359 private ValidationResult addSubGroup(SessionData data, PdpSubGroup subgrp) throws PfModelException {
360 subgrp.setCurrentInstanceCount(0);
361 subgrp.setPdpInstances(Collections.emptyList());
363 var result = new BeanValidationResult(subgrp.getPdpType(), subgrp);
365 result.addResult(validateSupportedTypes(data, subgrp));
370 * Updates an existing subgroup.
372 * @param dbsub the subgroup, from the DB
373 * @param subgrp the subgroup to be updated, updated to fully qualified versions upon
375 * @param container container for additional validation results
376 * @return {@code true} if the subgroup content was changed, {@code false} if there
379 private boolean updateSubGroup(PdpSubGroup dbsub, PdpSubGroup subgrp, BeanValidationResult container) {
381 // perform additional validations first
382 if (!validateSubGroup(dbsub, subgrp, container)) {
386 if (null != subgrp.getSupportedPolicyTypes() && !new HashSet<>(dbsub.getSupportedPolicyTypes())
387 .equals(new HashSet<>(subgrp.getSupportedPolicyTypes()))) {
388 logger.warn("Supported policy types cannot be updated while updating PdpGroup. "
389 + "Hence, ignoring the new set of supported policy types.");
392 // while updating PdpGroup, list of policies (already deployed ones) and supported policies (the ones provided
393 // during PdpGroup creation) has to be retained
394 subgrp.setSupportedPolicyTypes(dbsub.getSupportedPolicyTypes());
395 subgrp.setPolicies(dbsub.getPolicies());
396 return updateField(dbsub.getDesiredInstanceCount(), subgrp.getDesiredInstanceCount(),
397 dbsub::setDesiredInstanceCount);
401 * Performs additional validations of a subgroup.
403 * @param dbsub the subgroup, from the DB
404 * @param subgrp the subgroup to be validated, updated to fully qualified versions
406 * @param container container for additional validation results
407 * @return {@code true} if the subgroup is valid, {@code false} otherwise
409 private boolean validateSubGroup(PdpSubGroup dbsub, PdpSubGroup subgrp, BeanValidationResult container) {
411 var result = new BeanValidationResult(subgrp.getPdpType(), subgrp);
413 if (!Objects.equals(dbsub.getProperties(), subgrp.getProperties())) {
414 result.addResult("properties", "", ValidationStatus.INVALID, "cannot change properties");
417 container.addResult(result);
419 return result.isValid();
423 * Performs validations of the supported policy types within a subgroup.
425 * @param data session data
426 * @param subgrp the subgroup to be validated
427 * @param result the validation result
428 * @throws PfModelException if an error occurred
430 private ValidationResult validateSupportedTypes(SessionData data, PdpSubGroup subgrp) throws PfModelException {
431 var result = new BeanValidationResult(subgrp.getPdpType(), subgrp);
432 for (ToscaConceptIdentifier type : subgrp.getSupportedPolicyTypes()) {
433 if (!type.getName().endsWith(".*") && data.getPolicyType(type) == null) {
434 result.addResult("policy type", type, ValidationStatus.INVALID, "unknown policy type");
442 protected Updater makeUpdater(SessionData data, ToscaPolicy policy,
443 ToscaConceptIdentifierOptVersion desiredPolicy) {
444 throw new UnsupportedOperationException("makeUpdater should not be invoked");