Add and register DAO provider wrapper
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / startstop / PapActivator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  *  Modifications Copyright (C) 2019 AT&T Intellectual Property.
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.pap.main.startstop;
23
24 import java.util.Arrays;
25 import java.util.Base64;
26 import java.util.Properties;
27 import java.util.concurrent.atomic.AtomicReference;
28 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
29 import org.onap.policy.common.endpoints.event.comm.TopicSource;
30 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
31 import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher;
32 import org.onap.policy.common.parameters.ParameterService;
33 import org.onap.policy.common.utils.services.Registry;
34 import org.onap.policy.common.utils.services.ServiceManagerContainer;
35 import org.onap.policy.models.pdp.concepts.PdpStatus;
36 import org.onap.policy.models.pdp.enums.PdpMessageType;
37 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
38 import org.onap.policy.pap.main.PapConstants;
39 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
40 import org.onap.policy.pap.main.PolicyPapRuntimeException;
41 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
42 import org.onap.policy.pap.main.comm.Publisher;
43 import org.onap.policy.pap.main.comm.TimerManager;
44 import org.onap.policy.pap.main.parameters.PapParameterGroup;
45 import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams;
46 import org.onap.policy.pap.main.parameters.PdpParameters;
47 import org.onap.policy.pap.main.rest.PapRestServer;
48 import org.onap.policy.pap.main.rest.PapStatisticsManager;
49
50 /**
51  * This class wraps a distributor so that it can be activated as a complete service
52  * together with all its pap and forwarding handlers.
53  *
54  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
55  */
56 public class PapActivator extends ServiceManagerContainer {
57     private static final String[] MSG_TYPE_NAMES = {"messageName"};
58     private static final String[] REQ_ID_NAMES = {"response", "responseTo"};
59
60     private final PapParameterGroup papParameterGroup;
61
62     /**
63      * The PAP REST API server.
64      */
65     private PapRestServer restServer;
66
67     /**
68      * Listens for messages on the topic, decodes them into a {@link PdpStatus} message,
69      * and then dispatches them to {@link #reqIdDispatcher}.
70      */
71     private final MessageTypeDispatcher msgDispatcher;
72
73     /**
74      * Listens for {@link PdpStatus} messages and then routes them to the listener
75      * associated with the ID of the originating request.
76      */
77     private final RequestIdDispatcher<PdpStatus> reqIdDispatcher;
78
79     /**
80      * Instantiate the activator for policy pap as a complete service.
81      *
82      * @param papParameterGroup the parameters for the pap service
83      * @param topicProperties properties used to configure the topics
84      */
85     public PapActivator(final PapParameterGroup papParameterGroup, Properties topicProperties) {
86         super("Policy PAP");
87
88         TopicEndpoint.manager.addTopicSinks(topicProperties);
89         TopicEndpoint.manager.addTopicSources(topicProperties);
90
91         try {
92             this.papParameterGroup = papParameterGroup;
93             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
94             this.reqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
95
96         } catch (RuntimeException e) {
97             throw new PolicyPapRuntimeException(e);
98         }
99
100         papParameterGroup.getRestServerParameters().setName(papParameterGroup.getName());
101
102         // TODO add these to the json property file
103         PolicyModelsProviderParameters daoParams = new PolicyModelsProviderParameters();
104         daoParams.setDatabaseUrl("jdbc:h2:mem:testdb");
105         daoParams.setDatabaseUser("policy");
106         daoParams.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
107         daoParams.setPersistenceUnit("ToscaConceptTest");
108
109         final Object pdpUpdateLock = new Object();
110         PdpParameters pdpParams = papParameterGroup.getPdpParameters();
111         AtomicReference<Publisher> pdpPub = new AtomicReference<>();
112         AtomicReference<TimerManager> pdpUpdTimers = new AtomicReference<>();
113         AtomicReference<TimerManager> pdpStChgTimers = new AtomicReference<>();
114         AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>();
115
116         // @formatter:off
117         addAction("PAP parameters",
118             () -> ParameterService.register(papParameterGroup),
119             () -> ParameterService.deregister(papParameterGroup.getName()));
120
121         addAction("DAO Factory",
122             () -> daoFactory.set(new PolicyModelsProviderFactoryWrapper(daoParams)),
123             () -> daoFactory.get().close());
124
125         addAction("DAO Factory registration",
126             () -> Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daoFactory.get()),
127             () -> Registry.unregister(PapConstants.REG_PAP_DAO_FACTORY));
128
129         addAction("Request ID Dispatcher",
130             () -> msgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.reqIdDispatcher),
131             () -> msgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
132
133         addAction("Message Dispatcher",
134             () -> registerMsgDispatcher(),
135             () -> unregisterMsgDispatcher());
136
137         addAction("topics",
138             () -> TopicEndpoint.manager.start(),
139             () -> TopicEndpoint.manager.shutdown());
140
141         addAction("PAP statistics",
142             () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
143             () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
144
145         addAction("PDP publisher",
146             () -> {
147                 pdpPub.set(new Publisher(PapConstants.TOPIC_POLICY_PDP_PAP));
148                 startThread(pdpPub.get());
149             },
150             () -> pdpPub.get().stop());
151
152         addAction("PDP update timers",
153             () -> {
154                 pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs()));
155                 startThread(pdpUpdTimers.get());
156             },
157             () -> pdpUpdTimers.get().stop());
158
159         addAction("PDP state-change timers",
160             () -> {
161                 pdpStChgTimers.set(new TimerManager("state-change", pdpParams.getUpdateParameters().getMaxWaitMs()));
162                 startThread(pdpStChgTimers.get());
163             },
164             () -> pdpStChgTimers.get().stop());
165
166         addAction("PDP modification lock",
167             () -> Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, pdpUpdateLock),
168             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_LOCK));
169
170         addAction("PDP modification requests",
171             () -> Registry.register(PapConstants.REG_PDP_MODIFY_MAP, new PdpModifyRequestMap(
172                             new PdpModifyRequestMapParams()
173                                     .setModifyLock(pdpUpdateLock)
174                                     .setParams(pdpParams)
175                                     .setPublisher(pdpPub.get())
176                                     .setResponseDispatcher(reqIdDispatcher)
177                                     .setStateChangeTimers(pdpStChgTimers.get())
178                                     .setUpdateTimers(pdpUpdTimers.get()))),
179             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
180
181         addAction("Create REST server",
182             () -> {
183                 restServer = new PapRestServer(papParameterGroup.getRestServerParameters());
184             },
185             () -> {
186                 restServer = null;
187             });
188
189         addAction("REST server",
190             () -> restServer.start(),
191             () -> restServer.stop());
192         // @formatter:on
193     }
194
195     /**
196      * Starts a background thread.
197      *
198      * @param runner function to run in the background
199      */
200     private void startThread(Runnable runner) {
201         Thread thread = new Thread(runner);
202         thread.setDaemon(true);
203
204         thread.start();
205     }
206
207     /**
208      * Get the parameters used by the activator.
209      *
210      * @return the parameters of the activator
211      */
212     public PapParameterGroup getParameterGroup() {
213         return papParameterGroup;
214     }
215
216     /**
217      * Registers the dispatcher with the topic source(s).
218      */
219     private void registerMsgDispatcher() {
220         for (TopicSource source : TopicEndpoint.manager
221                         .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
222             source.register(msgDispatcher);
223         }
224     }
225
226     /**
227      * Unregisters the dispatcher from the topic source(s).
228      */
229     private void unregisterMsgDispatcher() {
230         for (TopicSource source : TopicEndpoint.manager
231                         .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
232             source.unregister(msgDispatcher);
233         }
234     }
235 }