Merge "Changed identifiers to concept identifiers"
[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 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.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
56     /**
57      * Lock used when updating PDPs.
58      */
59     private final Object updateLock;
60
61     /**
62      * Used to send UPDATE and STATE-CHANGE requests to the PDPs.
63      */
64     private final PdpModifyRequestMap requestMap;
65
66     /**
67      * Generates policy notifications based on responses from PDPs.
68      */
69     private final PolicyNotifier notifier;
70
71     /**
72      * Factory for PAP DAO.
73      */
74     private final PolicyModelsProviderFactoryWrapper daoFactory;
75
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
99             try (PolicyModelsProvider dao = daoFactory.create()) {
100
101                 data = new SessionData(dao);
102                 processor.accept(data, request);
103
104                 // make all of the DB updates
105                 data.updateDb();
106
107             } catch (PfModelException | PfModelRuntimeException e) {
108                 throw e;
109
110             } catch (RuntimeException e) {
111                 throw new PfModelException(Status.INTERNAL_SERVER_ERROR, "request failed", e);
112             }
113
114             // track responses for notification purposes
115             data.getDeployData().forEach(notifier::addDeploymentData);
116             data.getUndeployData().forEach(notifier::addUndeploymentData);
117
118             // publish the requests
119             data.getPdpRequests().forEach(pair -> requestMap.addRequest(pair.getLeft(), pair.getRight()));
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         Updater 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) throws PfModelException {
185
186         boolean updated = false;
187
188         for (PdpSubGroup subgroup : group.getPdpSubgroups()) {
189
190             if (!updater.apply(group, subgroup)) {
191                 continue;
192             }
193
194             updated = true;
195
196             makeUpdates(data, group, subgroup);
197         }
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         PdpUpdate 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
239         return update;
240     }
241
242     /**
243      * Gets the specified policy.
244      *
245      * @param data session data
246      * @param ident policy identifier, with an optional version
247      * @return the policy of interest
248      * @throws PfModelRuntimeException if an error occurred or the policy was not found
249      */
250     private ToscaPolicy getPolicy(SessionData data, ToscaConceptIdentifierOptVersion ident) {
251         try {
252             ToscaPolicy policy = data.getPolicy(ident);
253             if (policy == null) {
254                 throw new PfModelRuntimeException(Status.NOT_FOUND,
255                                 "cannot find policy: " + ident.getName() + " " + ident.getVersion());
256             }
257
258             return policy;
259
260         } catch (PfModelException e) {
261             throw new PfModelRuntimeException(e.getErrorResponse().getResponseCode(),
262                             e.getErrorResponse().getErrorMessage(), e);
263         }
264     }
265
266     @FunctionalInterface
267     public static interface BiConsumerWithEx<F, S> {
268         /**
269          * Performs this operation on the given arguments.
270          *
271          * @param firstArg the first input argument
272          * @param secondArg the second input argument
273          * @throws PfModelException if an error occurred
274          */
275         void accept(F firstArg, S secondArg) throws PfModelException;
276     }
277
278     @FunctionalInterface
279     public static interface Updater {
280         boolean apply(PdpGroup group, PdpSubGroup subgroup) throws PfModelException;
281     }
282 }