9494370645a8257a55c8fe7cf1aa250a5eca3722
[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.listeners.MessageTypeDispatcher;
34 import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher;
35 import org.onap.policy.common.parameters.ParameterService;
36 import org.onap.policy.common.utils.services.Registry;
37 import org.onap.policy.common.utils.services.ServiceManagerContainer;
38 import org.onap.policy.models.pap.concepts.PolicyNotification;
39 import org.onap.policy.models.pdp.concepts.PdpMessage;
40 import org.onap.policy.models.pdp.concepts.PdpStatus;
41 import org.onap.policy.models.pdp.enums.PdpMessageType;
42 import org.onap.policy.pap.main.PapConstants;
43 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
44 import org.onap.policy.pap.main.PolicyPapRuntimeException;
45 import org.onap.policy.pap.main.comm.PdpHeartbeatListener;
46 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
47 import org.onap.policy.pap.main.comm.Publisher;
48 import org.onap.policy.pap.main.comm.TimerManager;
49 import org.onap.policy.pap.main.notification.PolicyNotifier;
50 import org.onap.policy.pap.main.parameters.PapParameterGroup;
51 import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams;
52 import org.onap.policy.pap.main.rest.PapStatisticsManager;
53 import org.onap.policy.pap.main.rest.PolicyUndeployerImpl;
54 import org.springframework.context.event.ContextClosedEvent;
55 import org.springframework.context.event.ContextRefreshedEvent;
56 import org.springframework.context.event.EventListener;
57 import org.springframework.stereotype.Component;
58
59 /**
60  * This class activates Policy Administration (PAP) as a complete service together with all its controllers, listeners &
61  * handlers.
62  *
63  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
64  */
65 @Component
66 public class PapActivator extends ServiceManagerContainer {
67     private static final String[] MSG_TYPE_NAMES = { "messageName" };
68     private static final String[] REQ_ID_NAMES = { "response", "responseTo" };
69
70     /**
71      * Max number of heat beats that can be missed before PAP removes a PDP.
72      */
73     private static final int MAX_MISSED_HEARTBEATS = 3;
74
75     private PapParameterGroup papParameterGroup;
76
77     /**
78      * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then dispatches them to
79      * {@link #responseReqIdDispatcher}.
80      */
81     private final MessageTypeDispatcher responseMsgDispatcher;
82     private final MessageTypeDispatcher heartbeatMsgDispatcher;
83
84     /**
85      * Listens for {@link PdpStatus} messages and then routes them to the listener associated with the ID of the
86      * originating request.
87      */
88     private final RequestIdDispatcher<PdpStatus> responseReqIdDispatcher;
89     private final RequestIdDispatcher<PdpStatus> heartbeatReqIdDispatcher;
90
91     /**
92      * Listener for anonymous {@link PdpStatus} messages either for registration or heartbeat.
93      */
94     private final PdpHeartbeatListener pdpHeartbeatListener;
95
96     /**
97      * Instantiate the activator for policy pap as a complete service.
98      *
99      * @param papParameterGroup the parameters for the pap service
100      */
101     public PapActivator(PapParameterGroup papParameterGroup) {
102         super("Policy PAP");
103         this.papParameterGroup = papParameterGroup;
104         TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup());
105
106         try {
107             this.responseMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
108             this.heartbeatMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
109             this.responseReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
110             this.heartbeatReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
111             this.pdpHeartbeatListener = new PdpHeartbeatListener(papParameterGroup.getPdpParameters(),
112                             papParameterGroup.isSavePdpStatisticsInDb());
113
114         } catch (final RuntimeException e) {
115             throw new PolicyPapRuntimeException(e);
116         }
117
118
119         final var pdpUpdateLock = new Object();
120         final var pdpParams = papParameterGroup.getPdpParameters();
121         final AtomicReference<Publisher<PdpMessage>> pdpPub = new AtomicReference<>();
122         final AtomicReference<Publisher<PolicyNotification>> notifyPub = new AtomicReference<>();
123         final AtomicReference<TimerManager> pdpUpdTimers = new AtomicReference<>();
124         final AtomicReference<TimerManager> pdpStChgTimers = new AtomicReference<>();
125         final AtomicReference<ScheduledExecutorService> pdpExpirationTimer = new AtomicReference<>();
126         final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>();
127         final AtomicReference<PdpModifyRequestMap> requestMap = new AtomicReference<>();
128         final AtomicReference<PolicyNotifier> notifier = new AtomicReference<>();
129
130         // @formatter:off
131         addAction("PAP parameters",
132             () -> ParameterService.register(papParameterGroup),
133             () -> ParameterService.deregister(papParameterGroup.getName()));
134
135         addAction("DAO Factory",
136             () -> daoFactory.set(new PolicyModelsProviderFactoryWrapper(
137                                     papParameterGroup.getDatabaseProviderParameters())),
138             () -> daoFactory.get().close());
139
140         addAction("DAO Factory registration",
141             () -> Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daoFactory.get()),
142             () -> Registry.unregister(PapConstants.REG_PAP_DAO_FACTORY));
143
144         addAction("Pdp Heartbeat Listener",
145             () -> heartbeatReqIdDispatcher.register(pdpHeartbeatListener),
146             () -> heartbeatReqIdDispatcher.unregister(pdpHeartbeatListener));
147
148         addAction("Response Request ID Dispatcher",
149             () -> responseMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.responseReqIdDispatcher),
150             () -> responseMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
151
152         addAction("Heartbeat Request ID Dispatcher",
153             () -> heartbeatMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.heartbeatReqIdDispatcher),
154             () -> heartbeatMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
155
156         addAction("Response Message Dispatcher",
157             () -> registerMsgDispatcher(responseMsgDispatcher, PapConstants.TOPIC_POLICY_PDP_PAP),
158             () -> unregisterMsgDispatcher(responseMsgDispatcher, PapConstants.TOPIC_POLICY_PDP_PAP));
159
160         addAction("Heartbeat Message Dispatcher",
161             () -> registerMsgDispatcher(heartbeatMsgDispatcher, PapConstants.TOPIC_POLICY_HEARTBEAT),
162             () -> unregisterMsgDispatcher(heartbeatMsgDispatcher, PapConstants.TOPIC_POLICY_HEARTBEAT));
163
164         addAction("topics",
165             TopicEndpointManager.getManager()::start,
166             TopicEndpointManager.getManager()::shutdown);
167
168         addAction("PAP statistics",
169             () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
170             () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
171
172         addAction("PAP Activator",
173             () -> Registry.register(PapConstants.REG_PAP_ACTIVATOR, this),
174             () -> Registry.unregister(PapConstants.REG_PAP_ACTIVATOR));
175
176         addAction("PDP publisher",
177             () -> {
178                 pdpPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_PDP_PAP));
179                 startThread(pdpPub.get());
180             },
181             () -> pdpPub.get().stop());
182
183         addAction("Policy Notification publisher",
184             () -> {
185                 notifyPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_NOTIFICATION));
186                 startThread(notifyPub.get());
187                 notifier.set(new PolicyNotifier(notifyPub.get(), daoFactory.get()));
188             },
189             () -> notifyPub.get().stop());
190
191         addAction("Policy Notifier",
192             () -> Registry.register(PapConstants.REG_POLICY_NOTIFIER, notifier.get()),
193             () -> Registry.unregister(PapConstants.REG_POLICY_NOTIFIER));
194
195         addAction("PDP update timers",
196             () -> {
197                 pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs()));
198                 startThread(pdpUpdTimers.get());
199             },
200             () -> pdpUpdTimers.get().stop());
201
202         addAction("PDP state-change timers",
203             () -> {
204                 pdpStChgTimers.set(new TimerManager("state-change", pdpParams.getUpdateParameters().getMaxWaitMs()));
205                 startThread(pdpStChgTimers.get());
206             },
207             () -> pdpStChgTimers.get().stop());
208
209         addAction("PDP modification lock",
210             () -> Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, pdpUpdateLock),
211             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_LOCK));
212
213         addAction("PDP modification requests",
214             () -> {
215                 requestMap.set(new PdpModifyRequestMap(
216                             PdpModifyRequestMapParams.builder()
217                                     .maxPdpAgeMs(MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs())
218                                     .daoFactory(daoFactory.get())
219                                     .modifyLock(pdpUpdateLock)
220                                     .params(pdpParams)
221                                     .policyNotifier(notifier.get())
222                                     .pdpPublisher(pdpPub.get())
223                                     .responseDispatcher(responseReqIdDispatcher)
224                                     .stateChangeTimers(pdpStChgTimers.get())
225                                     .updateTimers(pdpUpdTimers.get())
226                                     .savePdpStatistics(papParameterGroup.isSavePdpStatisticsInDb())
227                                     .build()));
228                 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
229
230                 // now that it's registered, we can attach a "policy undeploy" provider
231                 requestMap.get().setPolicyUndeployer(new PolicyUndeployerImpl());
232             },
233             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
234
235         addAction("PDP expiration timer",
236             () -> {
237                 long frequencyMs = pdpParams.getHeartBeatMs();
238                 pdpExpirationTimer.set(Executors.newScheduledThreadPool(1));
239                 pdpExpirationTimer.get().scheduleWithFixedDelay(
240                     requestMap.get()::removeExpiredPdps,
241                     frequencyMs,
242                     frequencyMs,
243                     TimeUnit.MILLISECONDS);
244             },
245             () -> pdpExpirationTimer.get().shutdown());
246
247         // @formatter:on
248     }
249
250     /**
251      * Starts a background thread.
252      *
253      * @param runner function to run in the background
254      */
255     private void startThread(final Runnable runner) {
256         final var thread = new Thread(runner);
257         thread.setDaemon(true);
258
259         thread.start();
260     }
261
262     /**
263      * Get the parameters used by the activator.
264      *
265      * @return the parameters of the activator
266      */
267     public PapParameterGroup getParameterGroup() {
268         return papParameterGroup;
269     }
270
271     /**
272      * Registers the dispatcher with the topic source(s).
273      * @param dispatcher dispatcher to register
274      * @param topic topic of interest
275      */
276     private void registerMsgDispatcher(TopicListener dispatcher, String topic) {
277         for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
278             source.register(dispatcher);
279         }
280     }
281
282     /**
283      * Unregisters the dispatcher from the topic source(s).
284      * @param dispatcher dispatcher to unregister
285      * @param topic topic of interest
286      */
287     private void unregisterMsgDispatcher(TopicListener dispatcher, String topic) {
288         for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
289             source.unregister(dispatcher);
290         }
291     }
292
293     /**
294      * Handle ContextRefreshEvent.
295      *
296      * @param ctxRefreshedEvent the ContextRefreshedEvent
297      */
298     @EventListener
299     public void handleContextRefreshEvent(ContextRefreshedEvent ctxRefreshedEvent) {
300         if (!isAlive()) {
301             start();
302         }
303     }
304
305     /**
306      * Handle ContextClosedEvent.
307      *
308      * @param ctxClosedEvent the ContextClosedEvent
309      */
310     @EventListener
311     public void handleContextClosedEvent(ContextClosedEvent ctxClosedEvent) {
312         if (isAlive()) {
313             stop();
314         }
315     }
316 }