Add PDP heart beat expiration timer
[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 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
28 import org.onap.policy.common.endpoints.event.comm.TopicSource;
29 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
30 import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher;
31 import org.onap.policy.common.parameters.ParameterService;
32 import org.onap.policy.common.utils.services.Registry;
33 import org.onap.policy.common.utils.services.ServiceManagerContainer;
34 import org.onap.policy.models.pdp.concepts.PdpStatus;
35 import org.onap.policy.models.pdp.enums.PdpMessageType;
36 import org.onap.policy.pap.main.PapConstants;
37 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
38 import org.onap.policy.pap.main.PolicyPapRuntimeException;
39 import org.onap.policy.pap.main.comm.PdpHeartbeatListener;
40 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
41 import org.onap.policy.pap.main.comm.PdpTracker;
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     /**
61      * Max number of heat beats that can be missed before PAP removes a PDP.
62      */
63     private static final int MAX_MISSED_HEARTBEATS = 3;
64
65     private final PapParameterGroup papParameterGroup;
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<TimerManager> heartBeatTimers = new AtomicReference<>();
114         final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>();
115         final AtomicReference<PdpModifyRequestMap> requestMap = new AtomicReference<>();
116         final AtomicReference<PapRestServer> restServer = new AtomicReference<>();
117
118         // @formatter:off
119         addAction("PAP parameters",
120             () -> ParameterService.register(papParameterGroup),
121             () -> ParameterService.deregister(papParameterGroup.getName()));
122
123         addAction("DAO Factory",
124             () -> daoFactory.set(new PolicyModelsProviderFactoryWrapper(
125                                     papParameterGroup.getDatabaseProviderParameters())),
126             () -> daoFactory.get().close());
127
128         addAction("DAO Factory registration",
129             () -> Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daoFactory.get()),
130             () -> Registry.unregister(PapConstants.REG_PAP_DAO_FACTORY));
131
132         addAction("Pdp Heartbeat Listener",
133             () -> reqIdDispatcher.register(pdpHeartbeatListener),
134             () -> reqIdDispatcher.unregister(pdpHeartbeatListener));
135
136         addAction("Request ID Dispatcher",
137             () -> msgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.reqIdDispatcher),
138             () -> msgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
139
140         addAction("Message Dispatcher",
141             this::registerMsgDispatcher,
142             this::unregisterMsgDispatcher);
143
144         addAction("topics",
145             TopicEndpoint.manager::start,
146             TopicEndpoint.manager::shutdown);
147
148         addAction("PAP statistics",
149             () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
150             () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
151
152         addAction("PDP publisher",
153             () -> {
154                 pdpPub.set(new Publisher(PapConstants.TOPIC_POLICY_PDP_PAP));
155                 startThread(pdpPub.get());
156             },
157             () -> pdpPub.get().stop());
158
159         addAction("PDP heart beat timers",
160             () -> {
161                 long maxWaitHeartBeatMs = MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs();
162                 heartBeatTimers.set(new TimerManager("heart beat", maxWaitHeartBeatMs));
163                 startThread(heartBeatTimers.get());
164             },
165             () -> heartBeatTimers.get().stop());
166
167         addAction("PDP update timers",
168             () -> {
169                 pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs()));
170                 startThread(pdpUpdTimers.get());
171             },
172             () -> pdpUpdTimers.get().stop());
173
174         addAction("PDP state-change timers",
175             () -> {
176                 pdpStChgTimers.set(new TimerManager("state-change", pdpParams.getUpdateParameters().getMaxWaitMs()));
177                 startThread(pdpStChgTimers.get());
178             },
179             () -> pdpStChgTimers.get().stop());
180
181         addAction("PDP modification lock",
182             () -> Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, pdpUpdateLock),
183             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_LOCK));
184
185         addAction("PDP modification requests",
186             () -> {
187                 requestMap.set(new PdpModifyRequestMap(
188                             new PdpModifyRequestMapParams()
189                                     .setDaoFactory(daoFactory.get())
190                                     .setModifyLock(pdpUpdateLock)
191                                     .setParams(pdpParams)
192                                     .setPublisher(pdpPub.get())
193                                     .setResponseDispatcher(reqIdDispatcher)
194                                     .setStateChangeTimers(pdpStChgTimers.get())
195                                     .setUpdateTimers(pdpUpdTimers.get())));
196                 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
197             },
198             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
199
200         addAction("PDP heart beat tracker",
201             () -> Registry.register(PapConstants.REG_PDP_TRACKER, PdpTracker.builder()
202                                     .daoFactory(daoFactory.get())
203                                     .timers(heartBeatTimers.get())
204                                     .modifyLock(pdpUpdateLock)
205                                     .requestMap(requestMap.get())
206                                     .build()),
207             () -> Registry.unregister(PapConstants.REG_PDP_TRACKER));
208
209         addAction("REST server",
210             () -> {
211                 restServer.set(new PapRestServer(papParameterGroup.getRestServerParameters()));
212                 restServer.get().start();
213             },
214             () -> restServer.get().stop());
215         // @formatter:on
216     }
217
218     /**
219      * Starts a background thread.
220      *
221      * @param runner function to run in the background
222      */
223     private void startThread(final Runnable runner) {
224         final Thread thread = new Thread(runner);
225         thread.setDaemon(true);
226
227         thread.start();
228     }
229
230     /**
231      * Get the parameters used by the activator.
232      *
233      * @return the parameters of the activator
234      */
235     public PapParameterGroup getParameterGroup() {
236         return papParameterGroup;
237     }
238
239     /**
240      * Registers the dispatcher with the topic source(s).
241      */
242     private void registerMsgDispatcher() {
243         for (final TopicSource source : TopicEndpoint.manager
244                 .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
245             source.register(msgDispatcher);
246         }
247     }
248
249     /**
250      * Unregisters the dispatcher from the topic source(s).
251      */
252     private void unregisterMsgDispatcher() {
253         for (final TopicSource source : TopicEndpoint.manager
254                 .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
255             source.unregister(msgDispatcher);
256         }
257     }
258 }