Remove legacy operational policy from models
[policy/models.git] / models-provider / src / main / java / org / onap / policy / models / provider / impl / DatabasePolicyModelsProviderImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2020 Nordix Foundation.
4  *  Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
5  *  Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.models.provider.impl;
24
25 import java.util.Base64;
26 import java.util.Date;
27 import java.util.List;
28 import java.util.Properties;
29 import javax.ws.rs.core.Response;
30 import lombok.NonNull;
31 import org.eclipse.persistence.config.PersistenceUnitProperties;
32 import org.onap.policy.models.base.PfModelException;
33 import org.onap.policy.models.base.PfModelRuntimeException;
34 import org.onap.policy.models.dao.DaoParameters;
35 import org.onap.policy.models.dao.PfDao;
36 import org.onap.policy.models.dao.PfDaoFactory;
37 import org.onap.policy.models.dao.impl.DefaultPfDao;
38 import org.onap.policy.models.pdp.concepts.Pdp;
39 import org.onap.policy.models.pdp.concepts.PdpGroup;
40 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
41 import org.onap.policy.models.pdp.concepts.PdpStatistics;
42 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
43 import org.onap.policy.models.pdp.persistence.provider.PdpProvider;
44 import org.onap.policy.models.pdp.persistence.provider.PdpStatisticsProvider;
45 import org.onap.policy.models.provider.PolicyModelsProvider;
46 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter;
52 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
54 import org.onap.policy.models.tosca.authorative.provider.AuthorativeToscaProvider;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * This class provides an implementation of the Policy Models Provider for the ONAP Policy Framework that works towards
60  * a relational database.
61  *
62  * @author Liam Fallon (liam.fallon@est.tech)
63  */
64 public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider {
65
66     private static final Logger LOGGER = LoggerFactory.getLogger(DatabasePolicyModelsProviderImpl.class);
67
68     private final PolicyModelsProviderParameters parameters;
69
70     // Database connection and the DAO for reading and writing Policy Framework concepts
71     private PfDao pfDao;
72
73     /**
74      * Constructor that takes the parameters.
75      *
76      * @param parameters the parameters for the provider
77      */
78     public DatabasePolicyModelsProviderImpl(@NonNull final PolicyModelsProviderParameters parameters) {
79         this.parameters = parameters;
80     }
81
82     @Override
83     public void init() throws PfModelException {
84         LOGGER.debug("opening the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
85                 parameters.getPersistenceUnit());
86
87         if (pfDao != null) {
88             String errorMessage = "provider is already initialized";
89             LOGGER.warn(errorMessage);
90             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage);
91         }
92
93         // Parameters for the DAO
94         final DaoParameters daoParameters = new DaoParameters();
95         daoParameters.setPluginClass(DefaultPfDao.class.getName());
96         daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
97
98         // Decode the password using Base64
99         String decodedPassword = new String(Base64.getDecoder().decode(getValue(parameters.getDatabasePassword())));
100
101         // @formatter:off
102         Properties jdbcProperties = new Properties();
103         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER,   parameters.getDatabaseDriver());
104         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL,      parameters.getDatabaseUrl());
105         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER,     parameters.getDatabaseUser());
106         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, decodedPassword);
107         // @formatter:on
108
109         daoParameters.setJdbcProperties(jdbcProperties);
110
111         try {
112             pfDao = new PfDaoFactory().createPfDao(daoParameters);
113             pfDao.init(daoParameters);
114         } catch (Exception exc) {
115             String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
116                     + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
117
118             this.close();
119             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
120         }
121     }
122
123     private String getValue(final String value) {
124         if (value != null && value.startsWith("${") && value.endsWith("}")) {
125             return System.getenv(value.substring(2, value.length() - 1));
126         }
127         return value;
128     }
129
130     @Override
131     public void close() throws PfModelException {
132         LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
133                 parameters.getPersistenceUnit());
134
135         if (pfDao != null) {
136             pfDao.close();
137             pfDao = null;
138         }
139
140         LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
141                 parameters.getPersistenceUnit());
142     }
143
144     @Override
145     public ToscaServiceTemplate getPolicyTypes(final String name, final String version) throws PfModelException {
146         assertInitialized();
147         return new AuthorativeToscaProvider().getPolicyTypes(pfDao, name, version);
148     }
149
150     @Override
151     public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException {
152         assertInitialized();
153         return new AuthorativeToscaProvider().getPolicyTypeList(pfDao, name, version);
154     }
155
156     @Override
157     public ToscaServiceTemplate getFilteredPolicyTypes(@NonNull ToscaPolicyTypeFilter filter) throws PfModelException {
158         assertInitialized();
159         return new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao, filter);
160     }
161
162     @Override
163     public List<ToscaPolicyType> getFilteredPolicyTypeList(@NonNull ToscaPolicyTypeFilter filter)
164             throws PfModelException {
165         assertInitialized();
166         return new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, filter);
167     }
168
169     @Override
170     public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
171             throws PfModelException {
172         assertInitialized();
173         return new AuthorativeToscaProvider().createPolicyTypes(pfDao, serviceTemplate);
174     }
175
176     @Override
177     public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
178             throws PfModelException {
179         assertInitialized();
180         return new AuthorativeToscaProvider().updatePolicyTypes(pfDao, serviceTemplate);
181     }
182
183     @Override
184     public ToscaServiceTemplate deletePolicyType(@NonNull final String name, @NonNull final String version)
185             throws PfModelException {
186         assertInitialized();
187
188         ToscaPolicyTypeIdentifier policyTypeIdentifier = new ToscaPolicyTypeIdentifier(name, version);
189         assertPolicyTypeNotSupportedInPdpGroup(policyTypeIdentifier);
190
191         return new AuthorativeToscaProvider().deletePolicyType(pfDao, name, version);
192     }
193
194     @Override
195     public ToscaServiceTemplate getPolicies(final String name, final String version) throws PfModelException {
196         assertInitialized();
197         return new AuthorativeToscaProvider().getPolicies(pfDao, name, version);
198     }
199
200     @Override
201     public List<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException {
202         assertInitialized();
203         return new AuthorativeToscaProvider().getPolicyList(pfDao, name, version);
204     }
205
206     @Override
207     public ToscaServiceTemplate getFilteredPolicies(@NonNull ToscaPolicyFilter filter) throws PfModelException {
208         assertInitialized();
209         return new AuthorativeToscaProvider().getFilteredPolicies(pfDao, filter);
210     }
211
212     @Override
213     public List<ToscaPolicy> getFilteredPolicyList(@NonNull ToscaPolicyFilter filter) throws PfModelException {
214         assertInitialized();
215         return new AuthorativeToscaProvider().getFilteredPolicyList(pfDao, filter);
216     }
217
218     @Override
219     public ToscaServiceTemplate createPolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
220             throws PfModelException {
221         assertInitialized();
222         return new AuthorativeToscaProvider().createPolicies(pfDao, serviceTemplate);
223     }
224
225     @Override
226     public ToscaServiceTemplate updatePolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
227             throws PfModelException {
228         assertInitialized();
229         return new AuthorativeToscaProvider().updatePolicies(pfDao, serviceTemplate);
230     }
231
232     @Override
233     public ToscaServiceTemplate deletePolicy(@NonNull final String name, @NonNull final String version)
234             throws PfModelException {
235         assertInitialized();
236
237         ToscaPolicyIdentifier policyIdentifier = new ToscaPolicyIdentifier(name, version);
238         assertPolicyNotDeployedInPdpGroup(policyIdentifier);
239
240         return new AuthorativeToscaProvider().deletePolicy(pfDao, name, version);
241     }
242
243     @Override
244     public List<PdpGroup> getPdpGroups(final String name) throws PfModelException {
245         assertInitialized();
246         return new PdpProvider().getPdpGroups(pfDao, name);
247     }
248
249     @Override
250     public List<PdpGroup> getFilteredPdpGroups(@NonNull PdpGroupFilter filter) throws PfModelException {
251         assertInitialized();
252         return new PdpProvider().getFilteredPdpGroups(pfDao, filter);
253     }
254
255     @Override
256     public List<PdpGroup> createPdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
257         assertInitialized();
258         return new PdpProvider().createPdpGroups(pfDao, pdpGroups);
259     }
260
261     @Override
262     public List<PdpGroup> updatePdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
263         assertInitialized();
264         return new PdpProvider().updatePdpGroups(pfDao, pdpGroups);
265     }
266
267     @Override
268     public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final PdpSubGroup pdpSubGroup)
269             throws PfModelException {
270         assertInitialized();
271         new PdpProvider().updatePdpSubGroup(pfDao, pdpGroupName, pdpSubGroup);
272     }
273
274     @Override
275     public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpSubGroup, @NonNull Pdp pdp)
276             throws PfModelException {
277         new PdpProvider().updatePdp(pfDao, pdpGroupName, pdpSubGroup, pdp);
278     }
279
280     @Override
281     public PdpGroup deletePdpGroup(@NonNull final String name) throws PfModelException {
282         assertInitialized();
283         return new PdpProvider().deletePdpGroup(pfDao, name);
284     }
285
286     @Override
287     public List<PdpStatistics> getPdpStatistics(final String name, final Date timestamp) throws PfModelException {
288         assertInitialized();
289         return new PdpStatisticsProvider().getPdpStatistics(pfDao, name, timestamp);
290     }
291
292     @Override
293     public List<PdpStatistics> getFilteredPdpStatistics(final String name, @NonNull final String pdpGroupName,
294             final String pdpSubGroup, final Date startTimeStamp, final Date endTimeStamp, final String sortOrder,
295             final int getRecordNum) throws PfModelException {
296         assertInitialized();
297         return new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, name, pdpGroupName, pdpSubGroup,
298                 startTimeStamp, endTimeStamp, sortOrder, getRecordNum);
299     }
300
301     @Override
302     public List<PdpStatistics> createPdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
303             throws PfModelException {
304         assertInitialized();
305         return new PdpStatisticsProvider().createPdpStatistics(pfDao, pdpStatisticsList);
306     }
307
308     @Override
309     public List<PdpStatistics> updatePdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
310             throws PfModelException {
311         assertInitialized();
312         return new PdpStatisticsProvider().updatePdpStatistics(pfDao, pdpStatisticsList);
313     }
314
315     @Override
316     public List<PdpStatistics> deletePdpStatistics(@NonNull final String name, final Date timestamp)
317             throws PfModelException {
318         assertInitialized();
319         return new PdpStatisticsProvider().deletePdpStatistics(pfDao, name, timestamp);
320     }
321
322     /**
323      * Check if the model provider is initialized.
324      */
325     private void assertInitialized() {
326         if (pfDao == null) {
327             String errorMessage = "policy models provider is not initilaized";
328             LOGGER.warn(errorMessage);
329             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
330         }
331     }
332
333     /**
334      * Assert that the policy type is not supported in any PDP group.
335      *
336      * @param policyTypeIdentifier the policy type identifier
337      * @throws PfModelException if the policy type is supported in a PDP group
338      */
339     private void assertPolicyTypeNotSupportedInPdpGroup(ToscaPolicyTypeIdentifier policyTypeIdentifier)
340             throws PfModelException {
341         for (PdpGroup pdpGroup : getPdpGroups(null)) {
342             for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
343                 if (pdpSubGroup.getSupportedPolicyTypes().contains(policyTypeIdentifier)) {
344                     throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE,
345                             "policy type is in use, it is referenced in PDP group " + pdpGroup.getName() + " subgroup "
346                                     + pdpSubGroup.getPdpType());
347                 }
348             }
349         }
350     }
351
352     /**
353      * Assert that the policy is not deployed in a PDP group.
354      *
355      * @param policyIdentifier the identifier of the policy
356      * @throws PfModelException thrown if the policy is deployed in a PDP group
357      */
358     private void assertPolicyNotDeployedInPdpGroup(final ToscaPolicyIdentifier policyIdentifier)
359             throws PfModelException {
360         for (PdpGroup pdpGroup : getPdpGroups(null)) {
361             for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
362                 if (pdpSubGroup.getPolicies().contains(policyIdentifier)) {
363                     throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE,
364                             "policy is in use, it is deployed in PDP group " + pdpGroup.getName() + " subgroup "
365                                     + pdpSubGroup.getPdpType());
366                 }
367             }
368         }
369     }
370 }