Cleanup the sonar issues in PAP
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / rest / PdpGroupCreateOrUpdateProvider.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation.
6  * Modifications Copyright (C) 2019 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
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21
22 package org.onap.policy.pap.main.rest;
23
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Objects;
30 import java.util.Set;
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.ObjectValidationResult;
36 import org.onap.policy.common.parameters.ValidationResult;
37 import org.onap.policy.common.parameters.ValidationStatus;
38 import org.onap.policy.common.utils.services.Registry;
39 import org.onap.policy.models.base.PfModelException;
40 import org.onap.policy.models.pdp.concepts.Pdp;
41 import org.onap.policy.models.pdp.concepts.PdpGroup;
42 import org.onap.policy.models.pdp.concepts.PdpGroups;
43 import org.onap.policy.models.pdp.concepts.PdpStateChange;
44 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
45 import org.onap.policy.models.pdp.concepts.PdpUpdate;
46 import org.onap.policy.models.pdp.enums.PdpState;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * Provider for PAP component to create or update PDP groups. The following items must be in the
56  * {@link Registry}:
57  * <ul>
58  * <li>PDP Modification Lock</li>
59  * <li>PDP Modify Request Map</li>
60  * <li>PAP DAO Factory</li>
61  * </ul>
62  */
63 public class PdpGroupCreateOrUpdateProvider extends ProviderBase {
64     private static final Logger logger = LoggerFactory.getLogger(PdpGroupCreateOrUpdateProvider.class);
65
66     /**
67      * Constructs the object.
68      */
69     public PdpGroupCreateOrUpdateProvider() {
70         super();
71     }
72
73     /**
74      * Creates or updates PDP groups.
75      *
76      * @param groups PDP group configurations to be created or updated
77      * @throws PfModelException if an error occurred
78      */
79     public void createOrUpdateGroups(PdpGroups groups) throws PfModelException {
80         BeanValidationResult result = new BeanValidationResult("groups", groups);
81         groups.checkForDuplicateGroups(result);
82         if (!result.isValid()) {
83             String msg = result.getResult().trim();
84             logger.warn(msg);
85             throw new PfModelException(Status.BAD_REQUEST, msg);
86         }
87         // During PdpGroup create/update, policies are not supposed to be deployed/undeployed into the group.
88         // There is a separate API for this.
89         List<PdpSubGroup> subGroupsWithPolicies =
90             groups.getGroups().parallelStream().flatMap(group -> group.getPdpSubgroups().parallelStream())
91                 .filter(subGroup -> null != subGroup.getPolicies() && !subGroup.getPolicies().isEmpty())
92                 .collect(Collectors.toList());
93         if (!subGroupsWithPolicies.isEmpty()) {
94             logger.warn(
95                 "Policies cannot be deployed during PdpGroup Create/Update operation. Ignoring the list of policies");
96             subGroupsWithPolicies.forEach(subGroup -> subGroup.setPolicies(Collections.emptyList()));
97         }
98         process(groups, this::createOrUpdate);
99     }
100
101     /**
102      * Creates or updates PDP groups. This is the method that does the actual work.
103      *
104      * @param data session data
105      * @param groups PDP group configurations
106      * @throws PfModelException if an error occurred
107      */
108     private void createOrUpdate(SessionData data, PdpGroups groups) throws PfModelException {
109         BeanValidationResult result = new BeanValidationResult("groups", groups);
110
111         for (PdpGroup group : groups.getGroups()) {
112             PdpGroup dbgroup = data.getGroup(group.getName());
113             ValidationResult groupValidationResult;
114             if (dbgroup == null) {
115                 // create group flow
116                 groupValidationResult = group.validatePapRest(false);
117                 if (groupValidationResult.isValid()) {
118                     result.addResult(addGroup(data, group));
119                 } else {
120                     result.addResult(groupValidationResult);
121                 }
122
123             } else {
124                 // update group flow
125                 groupValidationResult = group.validatePapRest(true);
126                 if (groupValidationResult.isValid()) {
127                     result.addResult(updateGroup(data, dbgroup, group));
128                 } else {
129                     result.addResult(groupValidationResult);
130                 }
131             }
132         }
133
134         if (!result.isValid()) {
135             throw new PfModelException(Status.BAD_REQUEST, result.getResult().trim());
136         }
137     }
138
139     /**
140      * Adds a new group.
141      *
142      * @param data session data
143      * @param group the group to be added
144      * @return the validation result
145      * @throws PfModelException if an error occurred
146      */
147     private ValidationResult addGroup(SessionData data, PdpGroup group) throws PfModelException {
148         BeanValidationResult result = new BeanValidationResult(group.getName(), group);
149
150         validateGroupOnly(group, result);
151         if (!result.isValid()) {
152             return result;
153         }
154
155         // default to active
156         if (group.getPdpGroupState() == null) {
157             group.setPdpGroupState(PdpState.ACTIVE);
158         }
159
160         for (PdpSubGroup subgrp : group.getPdpSubgroups()) {
161             result.addResult(addSubGroup(data, subgrp));
162         }
163
164         if (result.isValid()) {
165             data.create(group);
166         }
167
168         return result;
169     }
170
171     /**
172      * Performs additional validations of a group, but does not examine the subgroups.
173      *
174      * @param group the group to be validated
175      * @param result the validation result
176      */
177     private void validateGroupOnly(PdpGroup group, BeanValidationResult result) {
178         if (group.getPdpGroupState() == null) {
179             return;
180         }
181
182         switch (group.getPdpGroupState()) {
183             case ACTIVE:
184             case PASSIVE:
185                 break;
186
187             default:
188                 result.addResult(new ObjectValidationResult("pdpGroupState", group.getPdpGroupState(),
189                     ValidationStatus.INVALID, "must be null, ACTIVE, or PASSIVE"));
190                 break;
191         }
192     }
193
194     /**
195      * Updates an existing group.
196      *
197      * @param data session data
198      * @param dbgroup the group, as it appears within the DB
199      * @param group the group to be added
200      * @return the validation result
201      * @throws PfModelException if an error occurred
202      */
203     private ValidationResult updateGroup(SessionData data, PdpGroup dbgroup, PdpGroup group) throws PfModelException {
204         BeanValidationResult result = new BeanValidationResult(group.getName(), group);
205
206         if (!Objects.equals(dbgroup.getProperties(), group.getProperties())) {
207             result.addResult(
208                 new ObjectValidationResult("properties", "", ValidationStatus.INVALID, "cannot change properties"));
209         }
210
211         boolean updated = updateField(dbgroup.getDescription(), group.getDescription(), dbgroup::setDescription);
212         updated =
213             updateField(dbgroup.getPdpGroupState(), group.getPdpGroupState(), dbgroup::setPdpGroupState) || updated;
214         updated = notifyPdpsDelSubGroups(data, dbgroup, group) || updated;
215         updated = addOrUpdateSubGroups(data, dbgroup, group, result) || updated;
216
217         if (result.isValid() && updated) {
218             data.update(group);
219         }
220
221         return result;
222     }
223
224     /**
225      * Updates a field, if the new value is different than the old value.
226      *
227      * @param oldValue old value
228      * @param newValue new value
229      * @param setter function to set the field to the new value
230      * @return {@code true} if the field was updated, {@code false} if it already matched
231      *         the new value
232      */
233     private <T> boolean updateField(T oldValue, T newValue, Consumer<T> setter) {
234         if (oldValue == newValue) {
235             return false;
236         }
237
238         if (oldValue != null && oldValue.equals(newValue)) {
239             return false;
240         }
241
242         setter.accept(newValue);
243         return true;
244     }
245
246     /**
247      * Adds or updates subgroups within the group.
248      *
249      * @param data session data
250      * @param dbgroup the group, as it appears within the DB
251      * @param group the group to be added
252      * @param result the validation result
253      * @return {@code true} if the DB group was modified, {@code false} otherwise
254      * @throws PfModelException if an error occurred
255      */
256     private boolean addOrUpdateSubGroups(SessionData data, PdpGroup dbgroup, PdpGroup group,
257         BeanValidationResult result) throws PfModelException {
258
259         // create a map of existing subgroups
260         Map<String, PdpSubGroup> type2sub = new HashMap<>();
261         dbgroup.getPdpSubgroups().forEach(subgrp -> type2sub.put(subgrp.getPdpType(), subgrp));
262
263         boolean updated = false;
264
265         for (PdpSubGroup subgrp : group.getPdpSubgroups()) {
266             PdpSubGroup dbsub = type2sub.get(subgrp.getPdpType());
267             BeanValidationResult subResult = new BeanValidationResult(subgrp.getPdpType(), subgrp);
268
269             if (dbsub == null) {
270                 updated = true;
271                 subResult.addResult(addSubGroup(data, subgrp));
272                 dbgroup.getPdpSubgroups().add(subgrp);
273
274             } else {
275                 updated = updateSubGroup(dbsub, subgrp, subResult) || updated;
276             }
277
278             result.addResult(subResult);
279         }
280
281         return updated;
282     }
283
284     /**
285      * Notifies any PDPs whose subgroups are being removed.
286      *
287      * @param data session data
288      * @param dbgroup the group, as it appears within the DB
289      * @param group the group being updated
290      * @return {@code true} if a subgroup was removed, {@code false} otherwise
291      * @throws PfModelException if an error occurred
292      */
293     private boolean notifyPdpsDelSubGroups(SessionData data, PdpGroup dbgroup, PdpGroup group) throws PfModelException {
294         boolean updated = false;
295
296         // subgroups, as they appear within the updated group
297         Set<String> subgroups = new HashSet<>();
298         group.getPdpSubgroups().forEach(subgrp -> subgroups.add(subgrp.getPdpType()));
299
300         // loop through subgroups as they appear within the DB
301         for (PdpSubGroup subgrp : dbgroup.getPdpSubgroups()) {
302
303             if (!subgroups.contains(subgrp.getPdpType())) {
304                 // this subgroup no longer appears - notify its PDPs
305                 updated = true;
306                 notifyPdpsDelSubGroup(data, subgrp);
307                 trackPdpsDelSubGroup(data, subgrp);
308             }
309         }
310
311         return updated;
312     }
313
314     /**
315      * Notifies the PDPs that their subgroup is being removed.
316      *
317      * @param data session data
318      * @param subgrp subgroup that is being removed
319      */
320     private void notifyPdpsDelSubGroup(SessionData data, PdpSubGroup subgrp) {
321         for (Pdp pdp : subgrp.getPdpInstances()) {
322             String name = pdp.getInstanceId();
323
324             // make it passive
325             PdpStateChange change = new PdpStateChange();
326             change.setName(name);
327             change.setState(PdpState.PASSIVE);
328
329             // remove it from subgroup and undeploy all policies
330             PdpUpdate update = new PdpUpdate();
331             update.setName(name);
332
333             data.addRequests(update, change);
334         }
335     }
336
337     /**
338      * Tracks PDP responses when their subgroup is removed.
339      *
340      * @param data session data
341      * @param subgrp subgroup that is being removed
342      * @throws PfModelException if an error occurred
343      */
344     private void trackPdpsDelSubGroup(SessionData data, PdpSubGroup subgrp) throws PfModelException {
345         Set<String> pdps = subgrp.getPdpInstances().stream().map(Pdp::getInstanceId).collect(Collectors.toSet());
346
347         for (ToscaPolicyIdentifier policyId : subgrp.getPolicies()) {
348             data.trackUndeploy(policyId, pdps);
349         }
350     }
351
352     /**
353      * Adds a new subgroup.
354      *
355      * @param data session data
356      * @param subgrp the subgroup to be added, updated to fully qualified versions upon
357      *        return
358      * @return the validation result
359      * @throws PfModelException if an error occurred
360      */
361     private ValidationResult addSubGroup(SessionData data, PdpSubGroup subgrp) throws PfModelException {
362         subgrp.setCurrentInstanceCount(0);
363         subgrp.setPdpInstances(Collections.emptyList());
364
365         BeanValidationResult result = new BeanValidationResult(subgrp.getPdpType(), subgrp);
366
367         result.addResult(validateSupportedTypes(data, subgrp));
368         return result;
369     }
370
371     /**
372      * Updates an existing subgroup.
373      *
374      * @param dbsub the subgroup, from the DB
375      * @param subgrp the subgroup to be updated, updated to fully qualified versions upon
376      *        return
377      * @param container container for additional validation results
378      * @return {@code true} if the subgroup content was changed, {@code false} if there
379      *         were no changes
380      */
381     private boolean updateSubGroup(PdpSubGroup dbsub, PdpSubGroup subgrp, BeanValidationResult container) {
382
383         // perform additional validations first
384         if (!validateSubGroup(dbsub, subgrp, container)) {
385             return false;
386         }
387
388         if (null != subgrp.getSupportedPolicyTypes() && !new HashSet<>(dbsub.getSupportedPolicyTypes())
389             .equals(new HashSet<>(subgrp.getSupportedPolicyTypes()))) {
390             logger.warn("Supported policy types cannot be updated while updating PdpGroup. "
391                 + "Hence, ignoring the new set of supported policy types.");
392         }
393
394         // while updating PdpGroup, list of policies (already deployed ones) and supported policies (the ones provided
395         // during PdpGroup creation) has to be retained
396         subgrp.setSupportedPolicyTypes(dbsub.getSupportedPolicyTypes());
397         subgrp.setPolicies(dbsub.getPolicies());
398         return updateField(dbsub.getDesiredInstanceCount(), subgrp.getDesiredInstanceCount(),
399             dbsub::setDesiredInstanceCount);
400     }
401
402     /**
403      * Performs additional validations of a subgroup.
404      *
405      * @param dbsub the subgroup, from the DB
406      * @param subgrp the subgroup to be validated, updated to fully qualified versions
407      *        upon return
408      * @param container container for additional validation results
409      * @return {@code true} if the subgroup is valid, {@code false} otherwise
410      */
411     private boolean validateSubGroup(PdpSubGroup dbsub, PdpSubGroup subgrp, BeanValidationResult container) {
412
413         BeanValidationResult result = new BeanValidationResult(subgrp.getPdpType(), subgrp);
414
415         if (!Objects.equals(dbsub.getProperties(), subgrp.getProperties())) {
416             result.addResult(
417                 new ObjectValidationResult("properties", "", ValidationStatus.INVALID, "cannot change properties"));
418         }
419
420         container.addResult(result);
421
422         return result.isValid();
423     }
424
425     /**
426      * Performs validations of the supported policy types within a subgroup.
427      *
428      * @param data session data
429      * @param subgrp the subgroup to be validated
430      * @param result the validation result
431      * @throws PfModelException if an error occurred
432      */
433     private ValidationResult validateSupportedTypes(SessionData data, PdpSubGroup subgrp) throws PfModelException {
434         BeanValidationResult result = new BeanValidationResult(subgrp.getPdpType(), subgrp);
435         for (ToscaPolicyTypeIdentifier type : subgrp.getSupportedPolicyTypes()) {
436             if (!type.getName().endsWith(".*") && data.getPolicyType(type) == null) {
437                 result.addResult(
438                     new ObjectValidationResult("policy type", type, ValidationStatus.INVALID, "unknown policy type"));
439             }
440         }
441
442         return result;
443     }
444
445     @Override
446     protected Updater makeUpdater(SessionData data, ToscaPolicy policy, ToscaPolicyIdentifierOptVersion desiredPolicy) {
447         throw new UnsupportedOperationException("makeUpdater should not be invoked");
448     }
449 }