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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.pap.main.startstop;
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;
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;
60 * This class activates Policy Administration (PAP) as a complete service together with all its controllers, listeners &
63 * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
66 public class PapActivator extends ServiceManagerContainer {
70 @Value("${pap.topic.pdp-pap.name}")
71 private String topicPolicyPdpPap = "policy-pdp-pap";
74 @Value("${pap.topic.notification.name}")
75 private String topicPolicyNotification = "policy-notification";
78 @Value("${pap.topic.heartbeat.name}")
79 private String topicPolicyHeartbeat = "policy-heartbeat";
81 private static final String[] MSG_TYPE_NAMES = { "messageName" };
82 private static final String[] REQ_ID_NAMES = { "response", "responseTo" };
85 * Max number of heart beats that can be missed before PAP removes a PDP.
87 private static final int MAX_MISSED_HEARTBEATS = 3;
89 private final PapParameterGroup papParameterGroup;
92 * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then dispatches them to
93 * {@link #responseReqIdDispatcher}.
95 private final MessageTypeDispatcher responseMsgDispatcher;
96 private final MessageTypeDispatcher heartbeatMsgDispatcher;
99 * Listens for {@link PdpStatus} messages and then routes them to the listener associated with the ID of the
100 * originating request.
102 private final RequestIdDispatcher<PdpStatus> responseReqIdDispatcher;
103 private final RequestIdDispatcher<PdpStatus> heartbeatReqIdDispatcher;
106 * Instantiate the activator for policy pap as a complete service.
108 * @param papParameterGroup the parameters for the pap service
110 public PapActivator(PapParameterGroup papParameterGroup, PolicyNotifier policyNotifier,
111 PdpHeartbeatListener pdpHeartbeatListener, PdpModifyRequestMap pdpModifyRequestMap,
112 MeterRegistry meterRegistry) {
114 this.papParameterGroup = papParameterGroup;
115 TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup());
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);
123 } catch (final RuntimeException e) {
124 throw new PolicyPapRuntimeException(e);
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<>();
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.
142 addAction("Meter Registry",
143 () -> Registry.register(PapConstants.REG_METER_REGISTRY, meterRegistry),
144 () -> Registry.unregister(PapConstants.REG_METER_REGISTRY));
146 addAction("PAP parameters",
147 () -> ParameterService.register(papParameterGroup),
148 () -> ParameterService.deregister(papParameterGroup.getName()));
150 addAction("Pdp Heartbeat Listener",
151 () -> heartbeatReqIdDispatcher.register(pdpHeartbeatListener),
152 () -> heartbeatReqIdDispatcher.unregister(pdpHeartbeatListener));
154 addAction("Response Request ID Dispatcher",
155 () -> responseMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.responseReqIdDispatcher),
156 () -> responseMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
158 addAction("Heartbeat Request ID Dispatcher",
159 () -> heartbeatMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.heartbeatReqIdDispatcher),
160 () -> heartbeatMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
162 addAction("Response Message Dispatcher",
163 () -> registerMsgDispatcher(responseMsgDispatcher, topicPolicyPdpPap),
164 () -> unregisterMsgDispatcher(responseMsgDispatcher, topicPolicyPdpPap));
166 addAction("Heartbeat Message Dispatcher",
167 () -> registerMsgDispatcher(heartbeatMsgDispatcher, topicPolicyHeartbeat),
168 () -> unregisterMsgDispatcher(heartbeatMsgDispatcher, topicPolicyHeartbeat));
171 TopicEndpointManager.getManager()::start,
172 TopicEndpointManager.getManager()::shutdown);
174 addAction("PAP Activator",
175 () -> Registry.register(PapConstants.REG_PAP_ACTIVATOR, this),
176 () -> Registry.unregister(PapConstants.REG_PAP_ACTIVATOR));
178 addAction("PDP publisher",
180 pdpPub.set(new Publisher<>(topicPolicyPdpPap));
181 startThread(pdpPub.get());
183 () -> pdpPub.get().stop());
185 addAction("Policy Notification publisher",
187 notifyPub.set(new Publisher<>(topicPolicyNotification));
188 startThread(notifyPub.get());
189 policyNotifier.setPublisher(notifyPub.get());
191 () -> notifyPub.get().stop());
193 addAction("PDP update timers",
195 pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs()));
196 startThread(pdpUpdTimers.get());
198 () -> pdpUpdTimers.get().stop());
200 addAction("PDP state-change timers",
202 pdpStChgTimers.set(new TimerManager("state-change", pdpParams.getUpdateParameters().getMaxWaitMs()));
203 startThread(pdpStChgTimers.get());
205 () -> pdpStChgTimers.get().stop());
207 addAction("PDP modification lock",
208 () -> Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, pdpUpdateLock),
209 () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_LOCK));
211 addAction("PDP modification requests",
213 pdpModifyRequestMap.initialize(
214 PdpModifyRequestMapParams.builder()
215 .maxPdpAgeMs(MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs())
216 .modifyLock(pdpUpdateLock)
218 .pdpPublisher(pdpPub.get())
219 .responseDispatcher(responseReqIdDispatcher)
220 .stateChangeTimers(pdpStChgTimers.get())
221 .updateTimers(pdpUpdTimers.get())
223 requestMap.set(pdpModifyRequestMap);
224 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
226 () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
228 addAction("PDP expiration timer",
230 long frequencyMs = pdpParams.getHeartBeatMs();
231 pdpExpirationTimer.set(Executors.newScheduledThreadPool(1));
232 pdpExpirationTimer.get().scheduleWithFixedDelay(
233 requestMap.get()::removeExpiredPdps,
236 TimeUnit.MILLISECONDS);
238 () -> pdpExpirationTimer.get().shutdown());
244 * Starts a background thread.
246 * @param runner function to run in the background
248 private void startThread(final Runnable runner) {
249 final var thread = new Thread(runner);
250 thread.setDaemon(true);
256 * Get the parameters used by the activator.
258 * @return the parameters of the activator
260 public PapParameterGroup getParameterGroup() {
261 return papParameterGroup;
265 * Registers the dispatcher with the topic source(s).
266 * @param dispatcher dispatcher to register
267 * @param topic topic of interest
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);
277 * Unregisters the dispatcher from the topic source(s).
278 * @param dispatcher dispatcher to unregister
279 * @param topic topic of interest
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);
289 * Handle ContextRefreshEvent.
291 * @param ctxRefreshedEvent the ContextRefreshedEvent
294 public void handleContextRefreshEvent(ContextRefreshedEvent ctxRefreshedEvent) {
301 * Handle ContextClosedEvent.
303 * @param ctxClosedEvent the ContextClosedEvent
306 public void handleContextClosedEvent(ContextClosedEvent ctxClosedEvent) {