2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 Nordix Foundation.
4 * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property.
5 * Modifications Copyright (C) 2021 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 java.util.List;
26 import java.util.concurrent.Executors;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.atomic.AtomicReference;
30 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
31 import org.onap.policy.common.endpoints.event.comm.TopicListener;
32 import org.onap.policy.common.endpoints.event.comm.TopicSource;
33 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
34 import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher;
35 import org.onap.policy.common.parameters.ParameterService;
36 import org.onap.policy.common.utils.services.Registry;
37 import org.onap.policy.common.utils.services.ServiceManagerContainer;
38 import org.onap.policy.models.pap.concepts.PolicyNotification;
39 import org.onap.policy.models.pdp.concepts.PdpMessage;
40 import org.onap.policy.models.pdp.concepts.PdpStatus;
41 import org.onap.policy.models.pdp.enums.PdpMessageType;
42 import org.onap.policy.pap.main.PapConstants;
43 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
44 import org.onap.policy.pap.main.PolicyPapRuntimeException;
45 import org.onap.policy.pap.main.comm.PdpHeartbeatListener;
46 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
47 import org.onap.policy.pap.main.comm.Publisher;
48 import org.onap.policy.pap.main.comm.TimerManager;
49 import org.onap.policy.pap.main.notification.PolicyNotifier;
50 import org.onap.policy.pap.main.parameters.PapParameterGroup;
51 import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams;
52 import org.onap.policy.pap.main.rest.PapStatisticsManager;
53 import org.onap.policy.pap.main.rest.PolicyUndeployerImpl;
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 {
67 private static final String[] MSG_TYPE_NAMES = { "messageName" };
68 private static final String[] REQ_ID_NAMES = { "response", "responseTo" };
71 * Max number of heat beats that can be missed before PAP removes a PDP.
73 private static final int MAX_MISSED_HEARTBEATS = 3;
75 private PapParameterGroup papParameterGroup;
78 * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then dispatches them to
79 * {@link #responseReqIdDispatcher}.
81 private final MessageTypeDispatcher responseMsgDispatcher;
82 private final MessageTypeDispatcher heartbeatMsgDispatcher;
85 * Listens for {@link PdpStatus} messages and then routes them to the listener associated with the ID of the
86 * originating request.
88 private final RequestIdDispatcher<PdpStatus> responseReqIdDispatcher;
89 private final RequestIdDispatcher<PdpStatus> heartbeatReqIdDispatcher;
92 * Listener for anonymous {@link PdpStatus} messages either for registration or heartbeat.
94 private final PdpHeartbeatListener pdpHeartbeatListener;
97 * Instantiate the activator for policy pap as a complete service.
99 * @param papParameterGroup the parameters for the pap service
101 public PapActivator(PapParameterGroup papParameterGroup) {
103 this.papParameterGroup = papParameterGroup;
104 TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup());
107 this.responseMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
108 this.heartbeatMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
109 this.responseReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
110 this.heartbeatReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
111 this.pdpHeartbeatListener = new PdpHeartbeatListener(papParameterGroup.getPdpParameters(),
112 papParameterGroup.isSavePdpStatisticsInDb());
114 } catch (final RuntimeException e) {
115 throw new PolicyPapRuntimeException(e);
119 final var pdpUpdateLock = new Object();
120 final var pdpParams = papParameterGroup.getPdpParameters();
121 final AtomicReference<Publisher<PdpMessage>> pdpPub = new AtomicReference<>();
122 final AtomicReference<Publisher<PolicyNotification>> notifyPub = new AtomicReference<>();
123 final AtomicReference<TimerManager> pdpUpdTimers = new AtomicReference<>();
124 final AtomicReference<TimerManager> pdpStChgTimers = new AtomicReference<>();
125 final AtomicReference<ScheduledExecutorService> pdpExpirationTimer = new AtomicReference<>();
126 final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>();
127 final AtomicReference<PdpModifyRequestMap> requestMap = new AtomicReference<>();
128 final AtomicReference<PolicyNotifier> notifier = new AtomicReference<>();
131 addAction("PAP parameters",
132 () -> ParameterService.register(papParameterGroup),
133 () -> ParameterService.deregister(papParameterGroup.getName()));
135 addAction("DAO Factory",
136 () -> daoFactory.set(new PolicyModelsProviderFactoryWrapper(
137 papParameterGroup.getDatabaseProviderParameters())),
138 () -> daoFactory.get().close());
140 addAction("DAO Factory registration",
141 () -> Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daoFactory.get()),
142 () -> Registry.unregister(PapConstants.REG_PAP_DAO_FACTORY));
144 addAction("Pdp Heartbeat Listener",
145 () -> heartbeatReqIdDispatcher.register(pdpHeartbeatListener),
146 () -> heartbeatReqIdDispatcher.unregister(pdpHeartbeatListener));
148 addAction("Response Request ID Dispatcher",
149 () -> responseMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.responseReqIdDispatcher),
150 () -> responseMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
152 addAction("Heartbeat Request ID Dispatcher",
153 () -> heartbeatMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.heartbeatReqIdDispatcher),
154 () -> heartbeatMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
156 addAction("Response Message Dispatcher",
157 () -> registerMsgDispatcher(responseMsgDispatcher, PapConstants.TOPIC_POLICY_PDP_PAP),
158 () -> unregisterMsgDispatcher(responseMsgDispatcher, PapConstants.TOPIC_POLICY_PDP_PAP));
160 addAction("Heartbeat Message Dispatcher",
161 () -> registerMsgDispatcher(heartbeatMsgDispatcher, PapConstants.TOPIC_POLICY_HEARTBEAT),
162 () -> unregisterMsgDispatcher(heartbeatMsgDispatcher, PapConstants.TOPIC_POLICY_HEARTBEAT));
165 TopicEndpointManager.getManager()::start,
166 TopicEndpointManager.getManager()::shutdown);
168 addAction("PAP statistics",
169 () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
170 () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
172 addAction("PAP Activator",
173 () -> Registry.register(PapConstants.REG_PAP_ACTIVATOR, this),
174 () -> Registry.unregister(PapConstants.REG_PAP_ACTIVATOR));
176 addAction("PDP publisher",
178 pdpPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_PDP_PAP));
179 startThread(pdpPub.get());
181 () -> pdpPub.get().stop());
183 addAction("Policy Notification publisher",
185 notifyPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_NOTIFICATION));
186 startThread(notifyPub.get());
187 notifier.set(new PolicyNotifier(notifyPub.get(), daoFactory.get()));
189 () -> notifyPub.get().stop());
191 addAction("Policy Notifier",
192 () -> Registry.register(PapConstants.REG_POLICY_NOTIFIER, notifier.get()),
193 () -> Registry.unregister(PapConstants.REG_POLICY_NOTIFIER));
195 addAction("PDP update timers",
197 pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs()));
198 startThread(pdpUpdTimers.get());
200 () -> pdpUpdTimers.get().stop());
202 addAction("PDP state-change timers",
204 pdpStChgTimers.set(new TimerManager("state-change", pdpParams.getUpdateParameters().getMaxWaitMs()));
205 startThread(pdpStChgTimers.get());
207 () -> pdpStChgTimers.get().stop());
209 addAction("PDP modification lock",
210 () -> Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, pdpUpdateLock),
211 () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_LOCK));
213 addAction("PDP modification requests",
215 requestMap.set(new PdpModifyRequestMap(
216 PdpModifyRequestMapParams.builder()
217 .maxPdpAgeMs(MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs())
218 .daoFactory(daoFactory.get())
219 .modifyLock(pdpUpdateLock)
221 .policyNotifier(notifier.get())
222 .pdpPublisher(pdpPub.get())
223 .responseDispatcher(responseReqIdDispatcher)
224 .stateChangeTimers(pdpStChgTimers.get())
225 .updateTimers(pdpUpdTimers.get())
226 .savePdpStatistics(papParameterGroup.isSavePdpStatisticsInDb())
228 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
230 // now that it's registered, we can attach a "policy undeploy" provider
231 requestMap.get().setPolicyUndeployer(new PolicyUndeployerImpl());
233 () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
235 addAction("PDP expiration timer",
237 long frequencyMs = pdpParams.getHeartBeatMs();
238 pdpExpirationTimer.set(Executors.newScheduledThreadPool(1));
239 pdpExpirationTimer.get().scheduleWithFixedDelay(
240 requestMap.get()::removeExpiredPdps,
243 TimeUnit.MILLISECONDS);
245 () -> pdpExpirationTimer.get().shutdown());
251 * Starts a background thread.
253 * @param runner function to run in the background
255 private void startThread(final Runnable runner) {
256 final var thread = new Thread(runner);
257 thread.setDaemon(true);
263 * Get the parameters used by the activator.
265 * @return the parameters of the activator
267 public PapParameterGroup getParameterGroup() {
268 return papParameterGroup;
272 * Registers the dispatcher with the topic source(s).
273 * @param dispatcher dispatcher to register
274 * @param topic topic of interest
276 private void registerMsgDispatcher(TopicListener dispatcher, String topic) {
277 for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
278 source.register(dispatcher);
283 * Unregisters the dispatcher from the topic source(s).
284 * @param dispatcher dispatcher to unregister
285 * @param topic topic of interest
287 private void unregisterMsgDispatcher(TopicListener dispatcher, String topic) {
288 for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
289 source.unregister(dispatcher);
294 * Handle ContextRefreshEvent.
296 * @param ctxRefreshedEvent the ContextRefreshedEvent
299 public void handleContextRefreshEvent(ContextRefreshedEvent ctxRefreshedEvent) {
306 * Handle ContextClosedEvent.
308 * @param ctxClosedEvent the ContextClosedEvent
311 public void handleContextClosedEvent(ContextClosedEvent ctxClosedEvent) {