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