19b3c672b4e6b51b905a222bac38be8a058832ce
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / startstop / PapActivator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019, 2022 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         addAction("Meter Registry",
141             () -> Registry.register(PapConstants.REG_METER_REGISTRY, meterRegistry),
142             () -> Registry.unregister(PapConstants.REG_METER_REGISTRY));
143
144         addAction("PAP parameters",
145             () -> ParameterService.register(papParameterGroup),
146             () -> ParameterService.deregister(papParameterGroup.getName()));
147
148         addAction("Pdp Heartbeat Listener",
149             () -> heartbeatReqIdDispatcher.register(pdpHeartbeatListener),
150             () -> heartbeatReqIdDispatcher.unregister(pdpHeartbeatListener));
151
152         addAction("Response Request ID Dispatcher",
153             () -> responseMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.responseReqIdDispatcher),
154             () -> responseMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
155
156         addAction("Heartbeat Request ID Dispatcher",
157             () -> heartbeatMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.heartbeatReqIdDispatcher),
158             () -> heartbeatMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
159
160         addAction("Response Message Dispatcher",
161             () -> registerMsgDispatcher(responseMsgDispatcher, topicPolicyPdpPap),
162             () -> unregisterMsgDispatcher(responseMsgDispatcher, topicPolicyPdpPap));
163
164         addAction("Heartbeat Message Dispatcher",
165             () -> registerMsgDispatcher(heartbeatMsgDispatcher, topicPolicyHeartbeat),
166             () -> unregisterMsgDispatcher(heartbeatMsgDispatcher, topicPolicyHeartbeat));
167
168         addAction("topics",
169             TopicEndpointManager.getManager()::start,
170             TopicEndpointManager.getManager()::shutdown);
171
172         addAction("PAP statistics",
173             () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
174             () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
175
176         addAction("PAP Activator",
177             () -> Registry.register(PapConstants.REG_PAP_ACTIVATOR, this),
178             () -> Registry.unregister(PapConstants.REG_PAP_ACTIVATOR));
179
180         addAction("PDP publisher",
181             () -> {
182                 pdpPub.set(new Publisher<>(topicPolicyPdpPap));
183                 startThread(pdpPub.get());
184             },
185             () -> pdpPub.get().stop());
186
187         addAction("Policy Notification publisher",
188             () -> {
189                 notifyPub.set(new Publisher<>(topicPolicyNotification));
190                 startThread(notifyPub.get());
191                 policyNotifier.setPublisher(notifyPub.get());
192             },
193             () -> notifyPub.get().stop());
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                 pdpModifyRequestMap.initialize(
216                     PdpModifyRequestMapParams.builder()
217                     .maxPdpAgeMs(MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs())
218                     .modifyLock(pdpUpdateLock)
219                     .params(pdpParams)
220                     .pdpPublisher(pdpPub.get())
221                     .responseDispatcher(responseReqIdDispatcher)
222                     .stateChangeTimers(pdpStChgTimers.get())
223                     .updateTimers(pdpUpdTimers.get())
224                     .savePdpStatistics(papParameterGroup.isSavePdpStatisticsInDb())
225                     .build());
226                 requestMap.set(pdpModifyRequestMap);
227                 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
228             },
229             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
230
231         addAction("PDP expiration timer",
232             () -> {
233                 long frequencyMs = pdpParams.getHeartBeatMs();
234                 pdpExpirationTimer.set(Executors.newScheduledThreadPool(1));
235                 pdpExpirationTimer.get().scheduleWithFixedDelay(
236                     requestMap.get()::removeExpiredPdps,
237                     frequencyMs,
238                     frequencyMs,
239                     TimeUnit.MILLISECONDS);
240             },
241             () -> pdpExpirationTimer.get().shutdown());
242
243         // @formatter:on
244     }
245
246     /**
247      * Starts a background thread.
248      *
249      * @param runner function to run in the background
250      */
251     private void startThread(final Runnable runner) {
252         final var thread = new Thread(runner);
253         thread.setDaemon(true);
254
255         thread.start();
256     }
257
258     /**
259      * Get the parameters used by the activator.
260      *
261      * @return the parameters of the activator
262      */
263     public PapParameterGroup getParameterGroup() {
264         return papParameterGroup;
265     }
266
267     /**
268      * Registers the dispatcher with the topic source(s).
269      * @param dispatcher dispatcher to register
270      * @param topic topic of interest
271      */
272     private void registerMsgDispatcher(TopicListener dispatcher, String topic) {
273         for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
274             source.register(dispatcher);
275         }
276     }
277
278     /**
279      * Unregisters the dispatcher from the topic source(s).
280      * @param dispatcher dispatcher to unregister
281      * @param topic topic of interest
282      */
283     private void unregisterMsgDispatcher(TopicListener dispatcher, String topic) {
284         for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
285             source.unregister(dispatcher);
286         }
287     }
288
289     /**
290      * Handle ContextRefreshEvent.
291      *
292      * @param ctxRefreshedEvent the ContextRefreshedEvent
293      */
294     @EventListener
295     public void handleContextRefreshEvent(ContextRefreshedEvent ctxRefreshedEvent) {
296         if (!isAlive()) {
297             start();
298         }
299     }
300
301     /**
302      * Handle ContextClosedEvent.
303      *
304      * @param ctxClosedEvent the ContextClosedEvent
305      */
306     @EventListener
307     public void handleContextClosedEvent(ContextClosedEvent ctxClosedEvent) {
308         if (isAlive()) {
309             stop();
310         }
311     }
312 }