Use separate subscription for heartbeats
[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-2021 AT&T Intellectual Property.
5  *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.startstop;
24
25 import java.util.List;
26 import java.util.concurrent.Executors;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.atomic.AtomicReference;
30 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
31 import org.onap.policy.common.endpoints.event.comm.TopicListener;
32 import org.onap.policy.common.endpoints.event.comm.TopicSource;
33 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
34 import org.onap.policy.common.endpoints.http.server.RestServer;
35 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
36 import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher;
37 import org.onap.policy.common.parameters.ParameterService;
38 import org.onap.policy.common.utils.services.Registry;
39 import org.onap.policy.common.utils.services.ServiceManagerContainer;
40 import org.onap.policy.models.pap.concepts.PolicyNotification;
41 import org.onap.policy.models.pdp.concepts.PdpMessage;
42 import org.onap.policy.models.pdp.concepts.PdpStatus;
43 import org.onap.policy.models.pdp.enums.PdpMessageType;
44 import org.onap.policy.pap.main.PapConstants;
45 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
46 import org.onap.policy.pap.main.PolicyPapRuntimeException;
47 import org.onap.policy.pap.main.comm.PdpHeartbeatListener;
48 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
49 import org.onap.policy.pap.main.comm.Publisher;
50 import org.onap.policy.pap.main.comm.TimerManager;
51 import org.onap.policy.pap.main.notification.PolicyNotifier;
52 import org.onap.policy.pap.main.parameters.PapParameterGroup;
53 import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams;
54 import org.onap.policy.pap.main.rest.HealthCheckRestControllerV1;
55 import org.onap.policy.pap.main.rest.PapAafFilter;
56 import org.onap.policy.pap.main.rest.PapStatisticsManager;
57 import org.onap.policy.pap.main.rest.PdpGroupCreateOrUpdateControllerV1;
58 import org.onap.policy.pap.main.rest.PdpGroupDeleteControllerV1;
59 import org.onap.policy.pap.main.rest.PdpGroupDeployControllerV1;
60 import org.onap.policy.pap.main.rest.PdpGroupHealthCheckControllerV1;
61 import org.onap.policy.pap.main.rest.PdpGroupQueryControllerV1;
62 import org.onap.policy.pap.main.rest.PdpGroupStateChangeControllerV1;
63 import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckControllerV1;
64 import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckProvider;
65 import org.onap.policy.pap.main.rest.PolicyStatusControllerV1;
66 import org.onap.policy.pap.main.rest.PolicyUndeployerImpl;
67 import org.onap.policy.pap.main.rest.StatisticsRestControllerV1;
68
69 /**
70  * This class activates Policy Administration (PAP) as a complete service together with all its controllers, listeners &
71  * handlers.
72  *
73  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
74  */
75 public class PapActivator extends ServiceManagerContainer {
76     private static final String[] MSG_TYPE_NAMES = { "messageName" };
77     private static final String[] REQ_ID_NAMES = { "response", "responseTo" };
78
79     /**
80      * Max number of heat beats that can be missed before PAP removes a PDP.
81      */
82     private static final int MAX_MISSED_HEARTBEATS = 3;
83
84     private final PapParameterGroup papParameterGroup;
85
86     /**
87      * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then dispatches them to
88      * {@link #responseReqIdDispatcher}.
89      */
90     private final MessageTypeDispatcher responseMsgDispatcher;
91     private final MessageTypeDispatcher heartbeatMsgDispatcher;
92
93     /**
94      * Listens for {@link PdpStatus} messages and then routes them to the listener associated with the ID of the
95      * originating request.
96      */
97     private final RequestIdDispatcher<PdpStatus> responseReqIdDispatcher;
98     private final RequestIdDispatcher<PdpStatus> heartbeatReqIdDispatcher;
99
100     /**
101      * Listener for anonymous {@link PdpStatus} messages either for registration or heartbeat.
102      */
103     private final PdpHeartbeatListener pdpHeartbeatListener;
104
105     /**
106      * Instantiate the activator for policy pap as a complete service.
107      *
108      * @param papParameterGroup the parameters for the pap service
109      */
110     public PapActivator(final PapParameterGroup papParameterGroup) {
111         super("Policy PAP");
112
113         TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup());
114
115         try {
116             this.papParameterGroup = papParameterGroup;
117             this.responseMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
118             this.heartbeatMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
119             this.responseReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
120             this.heartbeatReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
121             this.pdpHeartbeatListener = new PdpHeartbeatListener(papParameterGroup.getPdpParameters(),
122                             papParameterGroup.isSavePdpStatisticsInDb());
123
124         } catch (final RuntimeException e) {
125             throw new PolicyPapRuntimeException(e);
126         }
127
128         papParameterGroup.getRestServerParameters().setName(papParameterGroup.getName());
129
130         final var pdpUpdateLock = new Object();
131         final var pdpParams = papParameterGroup.getPdpParameters();
132         final AtomicReference<Publisher<PdpMessage>> pdpPub = new AtomicReference<>();
133         final AtomicReference<Publisher<PolicyNotification>> notifyPub = new AtomicReference<>();
134         final AtomicReference<TimerManager> pdpUpdTimers = new AtomicReference<>();
135         final AtomicReference<TimerManager> pdpStChgTimers = new AtomicReference<>();
136         final AtomicReference<ScheduledExecutorService> pdpExpirationTimer = new AtomicReference<>();
137         final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>();
138         final AtomicReference<PdpModifyRequestMap> requestMap = new AtomicReference<>();
139         final AtomicReference<RestServer> restServer = new AtomicReference<>();
140         final AtomicReference<PolicyNotifier> notifier = new AtomicReference<>();
141
142         // @formatter:off
143         addAction("PAP parameters",
144             () -> ParameterService.register(papParameterGroup),
145             () -> ParameterService.deregister(papParameterGroup.getName()));
146
147         addAction("DAO Factory",
148             () -> daoFactory.set(new PolicyModelsProviderFactoryWrapper(
149                                     papParameterGroup.getDatabaseProviderParameters())),
150             () -> daoFactory.get().close());
151
152         addAction("DAO Factory registration",
153             () -> Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daoFactory.get()),
154             () -> Registry.unregister(PapConstants.REG_PAP_DAO_FACTORY));
155
156         addAction("Pdp Heartbeat Listener",
157             () -> heartbeatReqIdDispatcher.register(pdpHeartbeatListener),
158             () -> heartbeatReqIdDispatcher.unregister(pdpHeartbeatListener));
159
160         addAction("Response Request ID Dispatcher",
161             () -> responseMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.responseReqIdDispatcher),
162             () -> responseMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
163
164         addAction("Heartbeat Request ID Dispatcher",
165             () -> heartbeatMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.heartbeatReqIdDispatcher),
166             () -> heartbeatMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
167
168         addAction("Response Message Dispatcher",
169             () -> registerMsgDispatcher(responseMsgDispatcher, PapConstants.TOPIC_POLICY_PDP_PAP),
170             () -> unregisterMsgDispatcher(responseMsgDispatcher, PapConstants.TOPIC_POLICY_PDP_PAP));
171
172         addAction("Heartbeat Message Dispatcher",
173             () -> registerMsgDispatcher(heartbeatMsgDispatcher, PapConstants.TOPIC_POLICY_HEARTBEAT),
174             () -> unregisterMsgDispatcher(heartbeatMsgDispatcher, PapConstants.TOPIC_POLICY_HEARTBEAT));
175
176         addAction("topics",
177             TopicEndpointManager.getManager()::start,
178             TopicEndpointManager.getManager()::shutdown);
179
180         addAction("PAP statistics",
181             () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
182             () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
183
184         addAction("PDP publisher",
185             () -> {
186                 pdpPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_PDP_PAP));
187                 startThread(pdpPub.get());
188             },
189             () -> pdpPub.get().stop());
190
191         addAction("Policy Notification publisher",
192             () -> {
193                 notifyPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_NOTIFICATION));
194                 startThread(notifyPub.get());
195                 notifier.set(new PolicyNotifier(notifyPub.get(), daoFactory.get()));
196             },
197             () -> notifyPub.get().stop());
198
199         addAction("Policy Notifier",
200             () -> Registry.register(PapConstants.REG_POLICY_NOTIFIER, notifier.get()),
201             () -> Registry.unregister(PapConstants.REG_POLICY_NOTIFIER));
202
203         addAction("PDP update timers",
204             () -> {
205                 pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs()));
206                 startThread(pdpUpdTimers.get());
207             },
208             () -> pdpUpdTimers.get().stop());
209
210         addAction("PDP state-change timers",
211             () -> {
212                 pdpStChgTimers.set(new TimerManager("state-change", pdpParams.getUpdateParameters().getMaxWaitMs()));
213                 startThread(pdpStChgTimers.get());
214             },
215             () -> pdpStChgTimers.get().stop());
216
217         addAction("PDP modification lock",
218             () -> Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, pdpUpdateLock),
219             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_LOCK));
220
221         addAction("PDP modification requests",
222             () -> {
223                 requestMap.set(new PdpModifyRequestMap(
224                             PdpModifyRequestMapParams.builder()
225                                     .maxPdpAgeMs(MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs())
226                                     .daoFactory(daoFactory.get())
227                                     .modifyLock(pdpUpdateLock)
228                                     .params(pdpParams)
229                                     .policyNotifier(notifier.get())
230                                     .pdpPublisher(pdpPub.get())
231                                     .responseDispatcher(responseReqIdDispatcher)
232                                     .stateChangeTimers(pdpStChgTimers.get())
233                                     .updateTimers(pdpUpdTimers.get())
234                                     .savePdpStatistics(papParameterGroup.isSavePdpStatisticsInDb())
235                                     .build()));
236                 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
237
238                 // now that it's registered, we can attach a "policy undeploy" provider
239                 requestMap.get().setPolicyUndeployer(new PolicyUndeployerImpl());
240             },
241             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
242
243         addAction("PDP expiration timer",
244             () -> {
245                 long frequencyMs = pdpParams.getHeartBeatMs();
246                 pdpExpirationTimer.set(Executors.newScheduledThreadPool(1));
247                 pdpExpirationTimer.get().scheduleWithFixedDelay(
248                     requestMap.get()::removeExpiredPdps,
249                     frequencyMs,
250                     frequencyMs,
251                     TimeUnit.MILLISECONDS);
252             },
253             () -> pdpExpirationTimer.get().shutdown());
254
255         addAction("PAP client executor",
256             () ->
257                 PolicyComponentsHealthCheckProvider.initializeClientHealthCheckExecutorService(papParameterGroup,
258                                 HttpClientFactoryInstance.getClientFactory()),
259                 PolicyComponentsHealthCheckProvider::cleanup);
260
261         addAction("REST server",
262             () -> {
263                 var server = new RestServer(papParameterGroup.getRestServerParameters(), PapAafFilter.class,
264                                 HealthCheckRestControllerV1.class,
265                                 StatisticsRestControllerV1.class,
266                                 PdpGroupCreateOrUpdateControllerV1.class,
267                                 PdpGroupDeployControllerV1.class,
268                                 PdpGroupDeleteControllerV1.class,
269                                 PdpGroupStateChangeControllerV1.class,
270                                 PdpGroupQueryControllerV1.class,
271                                 PdpGroupHealthCheckControllerV1.class,
272                                 PolicyStatusControllerV1.class,
273                                 PolicyComponentsHealthCheckControllerV1.class);
274                 restServer.set(server);
275                 restServer.get().start();
276             },
277             () -> restServer.get().stop());
278         // @formatter:on
279     }
280
281     /**
282      * Starts a background thread.
283      *
284      * @param runner function to run in the background
285      */
286     private void startThread(final Runnable runner) {
287         final var thread = new Thread(runner);
288         thread.setDaemon(true);
289
290         thread.start();
291     }
292
293     /**
294      * Get the parameters used by the activator.
295      *
296      * @return the parameters of the activator
297      */
298     public PapParameterGroup getParameterGroup() {
299         return papParameterGroup;
300     }
301
302     /**
303      * Registers the dispatcher with the topic source(s).
304      * @param dispatcher dispatcher to register
305      * @param topic topic of interest
306      */
307     private void registerMsgDispatcher(TopicListener dispatcher, String topic) {
308         for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
309             source.register(dispatcher);
310         }
311     }
312
313     /**
314      * Unregisters the dispatcher from the topic source(s).
315      * @param dispatcher dispatcher to unregister
316      * @param topic topic of interest
317      */
318     private void unregisterMsgDispatcher(TopicListener dispatcher, String topic) {
319         for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
320             source.unregister(dispatcher);
321         }
322     }
323 }