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
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.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;
61 * This class activates Policy Administration (PAP) as a complete service together with all its controllers, listeners &
64 * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
67 public class PapActivator extends ServiceManagerContainer {
71 @Value("${pap.topic.pdp-pap.name}")
72 private String topicPolicyPdpPap = "POLICY-PDP-PAP";
75 @Value("${pap.topic.notification.name}")
76 private String topicPolicyNotification = "POLICY-NOTIFICATION";
79 @Value("${pap.topic.heartbeat.name}")
80 private String topicPolicyHeartbeat = "POLICY-HEARTBEAT";
82 private static final String[] MSG_TYPE_NAMES = { "messageName" };
83 private static final String[] REQ_ID_NAMES = { "response", "responseTo" };
86 * Max number of heart beats that can be missed before PAP removes a PDP.
88 private static final int MAX_MISSED_HEARTBEATS = 3;
90 private final PapParameterGroup papParameterGroup;
93 * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then dispatches them to
94 * {@link #responseReqIdDispatcher}.
96 private final MessageTypeDispatcher responseMsgDispatcher;
97 private final MessageTypeDispatcher heartbeatMsgDispatcher;
100 * Listens for {@link PdpStatus} messages and then routes them to the listener associated with the ID of the
101 * originating request.
103 private final RequestIdDispatcher<PdpStatus> responseReqIdDispatcher;
104 private final RequestIdDispatcher<PdpStatus> heartbeatReqIdDispatcher;
107 * Instantiate the activator for policy pap as a complete service.
109 * @param papParameterGroup the parameters for the pap service
111 public PapActivator(PapParameterGroup papParameterGroup, PolicyNotifier policyNotifier,
112 PdpHeartbeatListener pdpHeartbeatListener, PdpModifyRequestMap pdpModifyRequestMap,
113 MeterRegistry meterRegistry) {
115 this.papParameterGroup = papParameterGroup;
116 TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup());
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);
124 } catch (final RuntimeException e) {
125 throw new PolicyPapRuntimeException(e);
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<>();
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.
143 addAction("Meter Registry",
144 () -> Registry.register(PapConstants.REG_METER_REGISTRY, meterRegistry),
145 () -> Registry.unregister(PapConstants.REG_METER_REGISTRY));
147 addAction("PAP parameters",
148 () -> ParameterService.register(papParameterGroup),
149 () -> ParameterService.deregister(papParameterGroup.getName()));
151 addAction("Pdp Heartbeat Listener",
152 () -> heartbeatReqIdDispatcher.register(pdpHeartbeatListener),
153 () -> heartbeatReqIdDispatcher.unregister(pdpHeartbeatListener));
155 addAction("Response Request ID Dispatcher",
156 () -> responseMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.responseReqIdDispatcher),
157 () -> responseMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
159 addAction("Heartbeat Request ID Dispatcher",
160 () -> heartbeatMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.heartbeatReqIdDispatcher),
161 () -> heartbeatMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
163 addAction("Response Message Dispatcher",
164 () -> registerMsgDispatcher(responseMsgDispatcher, topicPolicyPdpPap),
165 () -> unregisterMsgDispatcher(responseMsgDispatcher, topicPolicyPdpPap));
167 addAction("Heartbeat Message Dispatcher",
168 () -> registerMsgDispatcher(heartbeatMsgDispatcher, topicPolicyHeartbeat),
169 () -> unregisterMsgDispatcher(heartbeatMsgDispatcher, topicPolicyHeartbeat));
172 TopicEndpointManager.getManager()::start,
173 TopicEndpointManager.getManager()::shutdown);
175 addAction("PAP statistics",
176 () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
177 () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
179 addAction("PAP Activator",
180 () -> Registry.register(PapConstants.REG_PAP_ACTIVATOR, this),
181 () -> Registry.unregister(PapConstants.REG_PAP_ACTIVATOR));
183 addAction("PDP publisher",
185 pdpPub.set(new Publisher<>(topicPolicyPdpPap));
186 startThread(pdpPub.get());
188 () -> pdpPub.get().stop());
190 addAction("Policy Notification publisher",
192 notifyPub.set(new Publisher<>(topicPolicyNotification));
193 startThread(notifyPub.get());
194 policyNotifier.setPublisher(notifyPub.get());
196 () -> notifyPub.get().stop());
198 addAction("PDP update timers",
200 pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs()));
201 startThread(pdpUpdTimers.get());
203 () -> pdpUpdTimers.get().stop());
205 addAction("PDP state-change timers",
207 pdpStChgTimers.set(new TimerManager("state-change", pdpParams.getUpdateParameters().getMaxWaitMs()));
208 startThread(pdpStChgTimers.get());
210 () -> pdpStChgTimers.get().stop());
212 addAction("PDP modification lock",
213 () -> Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, pdpUpdateLock),
214 () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_LOCK));
216 addAction("PDP modification requests",
218 pdpModifyRequestMap.initialize(
219 PdpModifyRequestMapParams.builder()
220 .maxPdpAgeMs(MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs())
221 .modifyLock(pdpUpdateLock)
223 .pdpPublisher(pdpPub.get())
224 .responseDispatcher(responseReqIdDispatcher)
225 .stateChangeTimers(pdpStChgTimers.get())
226 .updateTimers(pdpUpdTimers.get())
227 .savePdpStatistics(papParameterGroup.isSavePdpStatisticsInDb())
229 requestMap.set(pdpModifyRequestMap);
230 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
232 () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
234 addAction("PDP expiration timer",
236 long frequencyMs = pdpParams.getHeartBeatMs();
237 pdpExpirationTimer.set(Executors.newScheduledThreadPool(1));
238 pdpExpirationTimer.get().scheduleWithFixedDelay(
239 requestMap.get()::removeExpiredPdps,
242 TimeUnit.MILLISECONDS);
244 () -> pdpExpirationTimer.get().shutdown());
250 * Starts a background thread.
252 * @param runner function to run in the background
254 private void startThread(final Runnable runner) {
255 final var thread = new Thread(runner);
256 thread.setDaemon(true);
262 * Get the parameters used by the activator.
264 * @return the parameters of the activator
266 public PapParameterGroup getParameterGroup() {
267 return papParameterGroup;
271 * Registers the dispatcher with the topic source(s).
272 * @param dispatcher dispatcher to register
273 * @param topic topic of interest
275 private void registerMsgDispatcher(TopicListener dispatcher, String topic) {
276 for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
277 source.register(dispatcher);
282 * Unregisters the dispatcher from the topic source(s).
283 * @param dispatcher dispatcher to unregister
284 * @param topic topic of interest
286 private void unregisterMsgDispatcher(TopicListener dispatcher, String topic) {
287 for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
288 source.unregister(dispatcher);
293 * Handle ContextRefreshEvent.
295 * @param ctxRefreshedEvent the ContextRefreshedEvent
298 public void handleContextRefreshEvent(ContextRefreshedEvent ctxRefreshedEvent) {
305 * Handle ContextClosedEvent.
307 * @param ctxClosedEvent the ContextClosedEvent
310 public void handleContextClosedEvent(ContextClosedEvent ctxClosedEvent) {