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