76ffd9ff71428e82b667709f94cff2d8115f32ae
[policy/api.git] / main / src / main / java / org / onap / policy / api / main / startstop / ApiDatabaseInitializer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy API
4  * ================================================================================
5  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019-2021 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.api.main.startstop;
25
26 import java.util.LinkedHashMap;
27 import java.util.LinkedList;
28 import java.util.List;
29 import org.onap.policy.api.main.exception.PolicyApiException;
30 import org.onap.policy.api.main.parameters.ApiParameterGroup;
31 import org.onap.policy.common.utils.coder.CoderException;
32 import org.onap.policy.common.utils.coder.StandardYamlCoder;
33 import org.onap.policy.common.utils.resources.ResourceUtils;
34 import org.onap.policy.models.base.PfModelException;
35 import org.onap.policy.models.base.PfModelRuntimeException;
36 import org.onap.policy.models.provider.PolicyModelsProvider;
37 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
38 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityFilter;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
40 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
41 import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * This class creates initial policy types in the database.
47  *
48  * @author Chenfei Gao (cgao@research.att.com)
49  */
50 public class ApiDatabaseInitializer {
51
52     private static final Logger LOGGER = LoggerFactory.getLogger(ApiDatabaseInitializer.class);
53
54     private static final StandardYamlCoder coder = new StandardYamlCoder();
55     private PolicyModelsProviderFactory factory;
56
57     /**
58      * Constructs the object.
59      */
60     public ApiDatabaseInitializer() {
61         factory = new PolicyModelsProviderFactory();
62     }
63
64     /**
65      * Initializes database by preloading policy types and policies.
66      *
67      * @param apiParameterGroup the apiParameterGroup parameters
68      * @throws PolicyApiException in case of errors.
69      */
70     public void initializeApiDatabase(final ApiParameterGroup apiParameterGroup) throws PolicyApiException {
71
72         try (var databaseProvider =
73                 factory.createPolicyModelsProvider(apiParameterGroup.getDatabaseProviderParameters())) {
74
75             if (alreadyExists(databaseProvider)) {
76                 LOGGER.warn("DB already contains policy data - skipping preload");
77                 return;
78             }
79
80             var serviceTemplate = new ToscaServiceTemplate();
81             serviceTemplate.setDataTypes(new LinkedHashMap<>());
82             serviceTemplate.setPolicyTypes(new LinkedHashMap<>());
83             serviceTemplate.setToscaDefinitionsVersion("tosca_simple_yaml_1_1_0");
84
85             ToscaServiceTemplate createdPolicyTypes = preloadServiceTemplate(serviceTemplate,
86                     apiParameterGroup.getPreloadPolicyTypes(), databaseProvider::createPolicyTypes);
87             preloadServiceTemplate(createdPolicyTypes, apiParameterGroup.getPreloadPolicies(),
88                     databaseProvider::createPolicies);
89         } catch (final PolicyApiException | PfModelException | CoderException exp) {
90             throw new PolicyApiException(exp);
91         }
92     }
93
94     private boolean alreadyExists(PolicyModelsProvider databaseProvider) throws PfModelException {
95         try {
96             ToscaServiceTemplate serviceTemplate =
97                     databaseProvider.getFilteredPolicyTypes(ToscaEntityFilter.<ToscaPolicyType>builder().build());
98             if (!serviceTemplate.getPolicyTypes().isEmpty()) {
99                 return true;
100             }
101
102         } catch (PfModelRuntimeException e) {
103             LOGGER.trace("DB does not yet contain policy types", e);
104         }
105
106         return false;
107     }
108
109     private ToscaServiceTemplate preloadServiceTemplate(ToscaServiceTemplate serviceTemplate, List<String> entities,
110             FunctionWithEx<ToscaServiceTemplate, ToscaServiceTemplate> getter)
111             throws PolicyApiException, CoderException, PfModelException {
112
113         for (String entity : entities) {
114             var entityAsStringYaml = ResourceUtils.getResourceAsString(entity);
115             if (entityAsStringYaml == null) {
116                 LOGGER.warn("Preloading entity cannot be found: {}", entity);
117                 continue;
118             }
119
120             ToscaServiceTemplate singleEntity = coder.decode(entityAsStringYaml, ToscaServiceTemplate.class);
121             if (singleEntity == null) {
122                 throw new PolicyApiException("Error deserializaing entity from file: " + entity);
123             }
124
125             // Consolidate data types and policy types
126             if (singleEntity.getDataTypes() != null) {
127                 serviceTemplate.getDataTypes().putAll(singleEntity.getDataTypes());
128             }
129             if (singleEntity.getPolicyTypes() != null) {
130                 serviceTemplate.getPolicyTypes().putAll(singleEntity.getPolicyTypes());
131             }
132
133             // Consolidate policies
134             var topologyTemplate = singleEntity.getToscaTopologyTemplate();
135             if (topologyTemplate != null && topologyTemplate.getPolicies() != null) {
136                 serviceTemplate.setToscaTopologyTemplate(new ToscaTopologyTemplate());
137                 serviceTemplate.getToscaTopologyTemplate().setPolicies(new LinkedList<>());
138                 serviceTemplate.getToscaTopologyTemplate().getPolicies()
139                         .addAll(singleEntity.getToscaTopologyTemplate().getPolicies());
140             }
141         }
142         // Preload the specified entities
143         ToscaServiceTemplate createdServiceTemplate = getter.apply(serviceTemplate);
144         LOGGER.debug("Created initial tosca service template in DB - {}", createdServiceTemplate);
145         return createdServiceTemplate;
146     }
147
148     @FunctionalInterface
149     protected interface FunctionWithEx<T, R> {
150         public R apply(T value) throws PfModelException;
151     }
152 }