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