Merge "Set DAO factory in request map parameters"
[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.PdpHeartbeatListener;
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 activates Policy Administration (PAP) as a complete service together with all its controllers, listeners &
52  * 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, and then dispatches them to
69      * {@link #reqIdDispatcher}.
70      */
71     private final MessageTypeDispatcher msgDispatcher;
72
73     /**
74      * Listens for {@link PdpStatus} messages and then routes them to the listener associated with the ID of the
75      * originating request.
76      */
77     private final RequestIdDispatcher<PdpStatus> reqIdDispatcher;
78
79     /**
80      * Listener for anonymous {@link PdpStatus} messages either for registration or heartbeat.
81      */
82     private final PdpHeartbeatListener pdpHeartbeatListener;
83
84     /**
85      * Instantiate the activator for policy pap as a complete service.
86      *
87      * @param papParameterGroup the parameters for the pap service
88      * @param topicProperties properties used to configure the topics
89      */
90     public PapActivator(final PapParameterGroup papParameterGroup, final Properties topicProperties) {
91         super("Policy PAP");
92
93         TopicEndpoint.manager.addTopicSinks(topicProperties);
94         TopicEndpoint.manager.addTopicSources(topicProperties);
95
96         try {
97             this.papParameterGroup = papParameterGroup;
98             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
99             this.reqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
100             this.pdpHeartbeatListener = new PdpHeartbeatListener();
101
102         } catch (final RuntimeException e) {
103             throw new PolicyPapRuntimeException(e);
104         }
105
106         papParameterGroup.getRestServerParameters().setName(papParameterGroup.getName());
107
108         final Object pdpUpdateLock = new Object();
109         final PdpParameters pdpParams = papParameterGroup.getPdpParameters();
110         final AtomicReference<Publisher> pdpPub = new AtomicReference<>();
111         final AtomicReference<TimerManager> pdpUpdTimers = new AtomicReference<>();
112         final AtomicReference<TimerManager> pdpStChgTimers = new AtomicReference<>();
113         final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>();
114
115         // @formatter:off
116         addAction("PAP parameters",
117             () -> ParameterService.register(papParameterGroup),
118             () -> ParameterService.deregister(papParameterGroup.getName()));
119
120         addAction("DAO Factory",
121             () -> daoFactory.set(new PolicyModelsProviderFactoryWrapper(
122                                     papParameterGroup.getDatabaseProviderParameters())),
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("Pdp Heartbeat Listener",
130             () -> reqIdDispatcher.register(pdpHeartbeatListener),
131             () -> reqIdDispatcher.unregister(pdpHeartbeatListener));
132
133         addAction("Request ID Dispatcher",
134             () -> msgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.reqIdDispatcher),
135             () -> msgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
136
137         addAction("Message Dispatcher",
138             this::registerMsgDispatcher,
139             this::unregisterMsgDispatcher);
140
141         addAction("topics",
142             TopicEndpoint.manager::start,
143             TopicEndpoint.manager::shutdown);
144
145         addAction("PAP statistics",
146             () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
147             () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
148
149         addAction("PDP publisher",
150             () -> {
151                 pdpPub.set(new Publisher(PapConstants.TOPIC_POLICY_PDP_PAP));
152                 startThread(pdpPub.get());
153             },
154             () -> pdpPub.get().stop());
155
156         addAction("PDP update timers",
157             () -> {
158                 pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs()));
159                 startThread(pdpUpdTimers.get());
160             },
161             () -> pdpUpdTimers.get().stop());
162
163         addAction("PDP state-change timers",
164             () -> {
165                 pdpStChgTimers.set(new TimerManager("state-change", pdpParams.getUpdateParameters().getMaxWaitMs()));
166                 startThread(pdpStChgTimers.get());
167             },
168             () -> pdpStChgTimers.get().stop());
169
170         addAction("PDP modification lock",
171             () -> Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, pdpUpdateLock),
172             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_LOCK));
173
174         addAction("PDP modification requests",
175             () -> Registry.register(PapConstants.REG_PDP_MODIFY_MAP, new PdpModifyRequestMap(
176                             new PdpModifyRequestMapParams()
177                                     .setDaoFactory(daoFactory.get())
178                                     .setModifyLock(pdpUpdateLock)
179                                     .setParams(pdpParams)
180                                     .setPublisher(pdpPub.get())
181                                     .setResponseDispatcher(reqIdDispatcher)
182                                     .setStateChangeTimers(pdpStChgTimers.get())
183                                     .setUpdateTimers(pdpUpdTimers.get()))),
184             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
185
186         addAction("Create REST server",
187             () -> restServer = new PapRestServer(papParameterGroup.getRestServerParameters()),
188             () -> restServer = null);
189
190         addAction("REST server",
191             () -> restServer.start(),
192             () -> restServer.stop());
193         // @formatter:on
194     }
195
196     /**
197      * Starts a background thread.
198      *
199      * @param runner function to run in the background
200      */
201     private void startThread(final Runnable runner) {
202         final Thread thread = new Thread(runner);
203         thread.setDaemon(true);
204
205         thread.start();
206     }
207
208     /**
209      * Get the parameters used by the activator.
210      *
211      * @return the parameters of the activator
212      */
213     public PapParameterGroup getParameterGroup() {
214         return papParameterGroup;
215     }
216
217     /**
218      * Registers the dispatcher with the topic source(s).
219      */
220     private void registerMsgDispatcher() {
221         for (final TopicSource source : TopicEndpoint.manager
222                 .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
223             source.register(msgDispatcher);
224         }
225     }
226
227     /**
228      * Unregisters the dispatcher from the topic source(s).
229      */
230     private void unregisterMsgDispatcher() {
231         for (final TopicSource source : TopicEndpoint.manager
232                 .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
233             source.unregister(msgDispatcher);
234         }
235     }
236 }