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