Merge "PolicyAudit creation when deploy/undeploy triggered."
[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 javax.ws.rs.core.Response.Status;
27 import org.onap.policy.common.utils.services.Registry;
28 import org.onap.policy.models.base.PfModelException;
29 import org.onap.policy.models.base.PfModelRuntimeException;
30 import org.onap.policy.models.pap.concepts.PolicyNotification;
31 import org.onap.policy.models.pdp.concepts.Pdp;
32 import org.onap.policy.models.pdp.concepts.PdpGroup;
33 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
34 import org.onap.policy.models.pdp.concepts.PdpUpdate;
35 import org.onap.policy.models.provider.PolicyModelsProvider;
36 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
37 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
38 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
39 import org.onap.policy.pap.main.PapConstants;
40 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
41 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
42 import org.onap.policy.pap.main.notification.PolicyNotifier;
43
44 /**
45  * Super class of providers that deploy and undeploy PDP groups. The following items must
46  * be in the {@link Registry}:
47  * <ul>
48  * <li>PDP Modification Lock</li>
49  * <li>PDP Modify Request Map</li>
50  * <li>PAP DAO Factory</li>
51  * </ul>
52  */
53 public abstract class ProviderBase {
54     public static final String DB_ERROR_MSG = "DB error";
55     public static final String DEFAULT_USER = "PAP";
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 user user triggering request
91      * @param request PDP policy request
92      * @param processor function that processes the request
93      * @throws PfModelException if an error occurred
94      */
95     protected <T> void process(String user, T request, BiConsumerWithEx<SessionData, T> processor)
96             throws PfModelException {
97
98         synchronized (updateLock) {
99             SessionData data;
100             var notif = new PolicyNotification();
101
102             try (PolicyModelsProvider dao = daoFactory.create()) {
103
104                 data = new SessionData(dao, user);
105                 processor.accept(data, request);
106
107                 // make all of the DB updates
108                 data.updateDb(notif);
109
110             } catch (PfModelException | PfModelRuntimeException e) {
111                 throw e;
112
113             } catch (RuntimeException e) {
114                 throw new PfModelException(Status.INTERNAL_SERVER_ERROR, "request failed", e);
115             }
116
117             // publish the requests
118             data.getPdpRequests().forEach(pair -> requestMap.addRequest(pair.getLeft(), pair.getRight()));
119
120             // publish the notifications
121             notifier.publish(notif);
122         }
123     }
124
125     /**
126      * Processes a policy request.
127      *
128      * @param request PDP policy request
129      * @param processor function that processes the request
130      * @throws PfModelException if an error occurred
131      */
132     protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException {
133         this.process(DEFAULT_USER, request, processor);
134     }
135
136     /**
137      * Process a single policy from the request.
138      *
139      * @param data session data
140      * @param desiredPolicy request policy
141      * @throws PfModelException if an error occurred
142      */
143     protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy)
144             throws PfModelException {
145
146         ToscaPolicy policy = getPolicy(data, desiredPolicy);
147
148         Collection<PdpGroup> groups = getGroups(data, policy.getTypeIdentifier());
149         if (groups.isEmpty()) {
150             throw new PfModelException(Status.BAD_REQUEST, "policy not supported by any PDP group: "
151                     + desiredPolicy.getName() + " " + desiredPolicy.getVersion());
152         }
153
154         var updater = makeUpdater(data, policy, desiredPolicy);
155
156         for (PdpGroup group : groups) {
157             upgradeGroup(data, group, updater);
158         }
159     }
160
161     /**
162      * Makes a function to update a subgroup. The function is expected to return
163      * {@code true} if the subgroup was updated, {@code false} if no update was
164      * necessary/appropriate.
165      *
166      * @param data session data
167      * @param policy policy to be added to or removed from each subgroup
168      * @param desiredPolicy request policy
169      * @return a function to update a subgroup
170      */
171     protected abstract Updater makeUpdater(SessionData data, ToscaPolicy policy,
172             ToscaConceptIdentifierOptVersion desiredPolicy);
173
174     /**
175      * Finds the active PDP group(s) that supports the given policy type.
176      *
177      * @param data session data
178      * @param policyType the policy type of interest
179      * @return the matching PDP group, or {@code null} if no active group supports the
180      *         given PDP types
181      * @throws PfModelException if an error occurred
182      */
183     private Collection<PdpGroup> getGroups(SessionData data, ToscaConceptIdentifier policyType)
184             throws PfModelException {
185
186         return data.getActivePdpGroupsByPolicyType(policyType);
187     }
188
189     /**
190      * Updates a group, assigning a new version number, if it actually changes.
191      *
192      * @param data session data
193      * @param group the original group, to be updated
194      * @param updater function to update a group
195      * @throws PfModelException if an error occurred
196      */
197     private void upgradeGroup(SessionData data, PdpGroup group, Updater updater) throws PfModelException {
198
199         var updated = false;
200
201         for (PdpSubGroup subgroup : group.getPdpSubgroups()) {
202
203             if (!updater.apply(group, subgroup)) {
204                 continue;
205             }
206
207             updated = true;
208
209             makeUpdates(data, group, subgroup);
210         }
211
212         if (updated) {
213             // something changed
214             data.update(group);
215         }
216     }
217
218     /**
219      * Makes UPDATE messages for each PDP in a subgroup.
220      *
221      * @param data session data
222      * @param group group containing the subgroup
223      * @param subgroup subgroup whose PDPs should receive messages
224      */
225     protected void makeUpdates(SessionData data, PdpGroup group, PdpSubGroup subgroup) {
226         for (Pdp pdp : subgroup.getPdpInstances()) {
227             data.addUpdate(makeUpdate(data, group, subgroup, pdp));
228         }
229     }
230
231     /**
232      * Makes an UPDATE message for a particular PDP.
233      *
234      * @param data session data
235      * @param group group to which the PDP should belong
236      * @param subgroup subgroup to which the PDP should belong
237      * @param pdp the PDP of interest
238      * @return a new UPDATE message
239      */
240     private PdpUpdate makeUpdate(SessionData data, PdpGroup group, PdpSubGroup subgroup, Pdp pdp) {
241
242         var update = new PdpUpdate();
243
244         update.setName(pdp.getInstanceId());
245         update.setDescription(group.getDescription());
246         update.setPdpGroup(group.getName());
247         update.setPdpSubgroup(subgroup.getPdpType());
248         update.setPoliciesToBeDeployed(data.getPoliciesToBeDeployed());
249         update.setPoliciesToBeUndeployed(data.getPoliciesToBeUndeployed());
250
251         return update;
252     }
253
254     /**
255      * Gets the specified policy.
256      *
257      * @param data session data
258      * @param ident policy identifier, with an optional version
259      * @return the policy of interest
260      * @throws PfModelRuntimeException if an error occurred or the policy was not found
261      */
262     private ToscaPolicy getPolicy(SessionData data, ToscaConceptIdentifierOptVersion ident) {
263         try {
264             ToscaPolicy policy = data.getPolicy(ident);
265             if (policy == null) {
266                 throw new PfModelRuntimeException(Status.NOT_FOUND,
267                         "cannot find policy: " + ident.getName() + " " + ident.getVersion());
268             }
269
270             return policy;
271
272         } catch (PfModelException e) {
273             throw new PfModelRuntimeException(e.getErrorResponse().getResponseCode(),
274                     e.getErrorResponse().getErrorMessage(), e);
275         }
276     }
277
278     @FunctionalInterface
279     public static interface BiConsumerWithEx<F, S> {
280         /**
281          * Performs this operation on the given arguments.
282          *
283          * @param firstArg the first input argument
284          * @param secondArg the second input argument
285          * @throws PfModelException if an error occurred
286          */
287         void accept(F firstArg, S secondArg) throws PfModelException;
288     }
289
290     @FunctionalInterface
291     public static interface Updater {
292         boolean apply(PdpGroup group, PdpSubGroup subgroup) throws PfModelException;
293     }
294 }