Fix sonars in policy-pap
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / rest / ProviderBase.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2020-2021 Nordix Foundation.
7  * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.rest;
24
25 import java.util.Collection;
26 import java.util.stream.Collectors;
27 import javax.ws.rs.core.Response.Status;
28 import org.onap.policy.common.utils.services.Registry;
29 import org.onap.policy.models.base.PfModelException;
30 import org.onap.policy.models.base.PfModelRuntimeException;
31 import org.onap.policy.models.pap.concepts.PolicyNotification;
32 import org.onap.policy.models.pdp.concepts.Pdp;
33 import org.onap.policy.models.pdp.concepts.PdpGroup;
34 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
35 import org.onap.policy.models.pdp.concepts.PdpUpdate;
36 import org.onap.policy.models.provider.PolicyModelsProvider;
37 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
38 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
40 import org.onap.policy.pap.main.PapConstants;
41 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
42 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
43 import org.onap.policy.pap.main.notification.PolicyNotifier;
44
45 /**
46  * Super class of providers that deploy and undeploy PDP groups. The following items must
47  * be in the {@link Registry}:
48  * <ul>
49  * <li>PDP Modification Lock</li>
50  * <li>PDP Modify Request Map</li>
51  * <li>PAP DAO Factory</li>
52  * </ul>
53  */
54 public abstract class ProviderBase {
55     public static final String DB_ERROR_MSG = "DB error";
56
57     /**
58      * Lock used when updating PDPs.
59      */
60     private final Object updateLock;
61
62     /**
63      * Used to send UPDATE and STATE-CHANGE requests to the PDPs.
64      */
65     private final PdpModifyRequestMap requestMap;
66
67     /**
68      * Generates policy notifications based on responses from PDPs.
69      */
70     private final PolicyNotifier notifier;
71
72     /**
73      * Factory for PAP DAO.
74      */
75     private final PolicyModelsProviderFactoryWrapper daoFactory;
76
77     /**
78      * Constructs the object.
79      */
80     protected ProviderBase() {
81         this.updateLock = Registry.get(PapConstants.REG_PDP_MODIFY_LOCK, Object.class);
82         this.requestMap = Registry.get(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class);
83         this.daoFactory = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class);
84         this.notifier = Registry.get(PapConstants.REG_POLICY_NOTIFIER, PolicyNotifier.class);
85     }
86
87     /**
88      * Processes a policy request.
89      *
90      * @param request PDP policy request
91      * @param processor function that processes the request
92      * @throws PfModelException if an error occurred
93      */
94     protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException {
95
96         synchronized (updateLock) {
97             SessionData data;
98             var notif = new PolicyNotification();
99
100             try (PolicyModelsProvider dao = daoFactory.create()) {
101
102                 data = new SessionData(dao);
103                 processor.accept(data, request);
104
105                 // make all of the DB updates
106                 data.updateDb(notif);
107
108             } catch (PfModelException | PfModelRuntimeException e) {
109                 throw e;
110
111             } catch (RuntimeException e) {
112                 throw new PfModelException(Status.INTERNAL_SERVER_ERROR, "request failed", e);
113             }
114
115             // publish the requests
116             data.getPdpRequests().forEach(pair -> requestMap.addRequest(pair.getLeft(), pair.getRight()));
117
118             // publish the notifications
119             notifier.publish(notif);
120         }
121     }
122
123     /**
124      * Process a single policy from the request.
125      *
126      * @param data session data
127      * @param desiredPolicy request policy
128      * @throws PfModelException if an error occurred
129      */
130     protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy)
131                     throws PfModelException {
132
133         ToscaPolicy policy = getPolicy(data, desiredPolicy);
134
135         Collection<PdpGroup> groups = getGroups(data, policy.getTypeIdentifier());
136         if (groups.isEmpty()) {
137             throw new PfModelException(Status.BAD_REQUEST, "policy not supported by any PDP group: "
138                             + desiredPolicy.getName() + " " + desiredPolicy.getVersion());
139         }
140
141         var updater = makeUpdater(data, policy, desiredPolicy);
142
143         for (PdpGroup group : groups) {
144             upgradeGroup(data, group, updater);
145         }
146     }
147
148     /**
149      * Makes a function to update a subgroup. The function is expected to return
150      * {@code true} if the subgroup was updated, {@code false} if no update was
151      * necessary/appropriate.
152      *
153      * @param data session data
154      * @param policy policy to be added to or removed from each subgroup
155      * @param desiredPolicy request policy
156      * @return a function to update a subgroup
157      */
158     protected abstract Updater makeUpdater(SessionData data, ToscaPolicy policy,
159                     ToscaConceptIdentifierOptVersion desiredPolicy);
160
161     /**
162      * Finds the active PDP group(s) that supports the given policy type.
163      *
164      * @param data session data
165      * @param policyType the policy type of interest
166      * @return the matching PDP group, or {@code null} if no active group supports the
167      *         given PDP types
168      * @throws PfModelException if an error occurred
169      */
170     private Collection<PdpGroup> getGroups(SessionData data, ToscaConceptIdentifier policyType)
171                     throws PfModelException {
172
173         return data.getActivePdpGroupsByPolicyType(policyType);
174     }
175
176     /**
177      * Updates a group, assigning a new version number, if it actually changes.
178      *
179      * @param data session data
180      * @param group the original group, to be updated
181      * @param updater function to update a group
182      * @throws PfModelException if an error occurred
183      */
184     private void upgradeGroup(SessionData data, PdpGroup group, Updater updater)
185                     throws PfModelException {
186
187         var updated = false;
188
189         for (PdpSubGroup subgroup : group.getPdpSubgroups()) {
190
191             if (!updater.apply(group, subgroup)) {
192                 continue;
193             }
194
195             updated = true;
196
197             makeUpdates(data, group, subgroup);
198         }
199
200         if (updated) {
201             // something changed
202             data.update(group);
203         }
204     }
205
206     /**
207      * Makes UPDATE messages for each PDP in a subgroup.
208      *
209      * @param data session data
210      * @param group group containing the subgroup
211      * @param subgroup subgroup whose PDPs should receive messages
212      */
213     protected void makeUpdates(SessionData data, PdpGroup group, PdpSubGroup subgroup) {
214         for (Pdp pdp : subgroup.getPdpInstances()) {
215             data.addUpdate(makeUpdate(data, group, subgroup, pdp));
216         }
217     }
218
219     /**
220      * Makes an UPDATE message for a particular PDP.
221      *
222      * @param data session data
223      * @param group group to which the PDP should belong
224      * @param subgroup subgroup to which the PDP should belong
225      * @param pdp the PDP of interest
226      * @return a new UPDATE message
227      */
228     private PdpUpdate makeUpdate(SessionData data, PdpGroup group, PdpSubGroup subgroup, Pdp pdp) {
229
230         var update = new PdpUpdate();
231
232         update.setName(pdp.getInstanceId());
233         update.setDescription(group.getDescription());
234         update.setPdpGroup(group.getName());
235         update.setPdpSubgroup(subgroup.getPdpType());
236         update.setPolicies(subgroup.getPolicies().stream().map(ToscaConceptIdentifierOptVersion::new)
237                         .map(ident -> getPolicy(data, ident)).collect(Collectors.toList()));
238         update.setPoliciesToBeDeployed(data.getPoliciesToBeDeployed());
239         update.setPoliciesToBeUndeployed(data.getPoliciesToBeUndeployed());
240
241         return update;
242     }
243
244     /**
245      * Gets the specified policy.
246      *
247      * @param data session data
248      * @param ident policy identifier, with an optional version
249      * @return the policy of interest
250      * @throws PfModelRuntimeException if an error occurred or the policy was not found
251      */
252     private ToscaPolicy getPolicy(SessionData data, ToscaConceptIdentifierOptVersion ident) {
253         try {
254             ToscaPolicy policy = data.getPolicy(ident);
255             if (policy == null) {
256                 throw new PfModelRuntimeException(Status.NOT_FOUND,
257                                 "cannot find policy: " + ident.getName() + " " + ident.getVersion());
258             }
259
260             return policy;
261
262         } catch (PfModelException e) {
263             throw new PfModelRuntimeException(e.getErrorResponse().getResponseCode(),
264                             e.getErrorResponse().getErrorMessage(), e);
265         }
266     }
267
268     @FunctionalInterface
269     public static interface BiConsumerWithEx<F, S> {
270         /**
271          * Performs this operation on the given arguments.
272          *
273          * @param firstArg the first input argument
274          * @param secondArg the second input argument
275          * @throws PfModelException if an error occurred
276          */
277         void accept(F firstArg, S secondArg) throws PfModelException;
278     }
279
280     @FunctionalInterface
281     public static interface Updater {
282         boolean apply(PdpGroup group, PdpSubGroup subgroup) throws PfModelException;
283     }
284 }