617275b4d7db5025753078cb0c4c6a1876c758b2
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / startstop / PapActivator.java
1 /*-
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
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 java.util.Arrays;
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.TopicSource;
32 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
33 import org.onap.policy.common.endpoints.http.server.RestServer;
34 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
35 import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher;
36 import org.onap.policy.common.parameters.ParameterService;
37 import org.onap.policy.common.utils.services.Registry;
38 import org.onap.policy.common.utils.services.ServiceManagerContainer;
39 import org.onap.policy.models.pap.concepts.PolicyNotification;
40 import org.onap.policy.models.pdp.concepts.PdpMessage;
41 import org.onap.policy.models.pdp.concepts.PdpStatus;
42 import org.onap.policy.models.pdp.enums.PdpMessageType;
43 import org.onap.policy.pap.main.PapConstants;
44 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
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.HealthCheckRestControllerV1;
54 import org.onap.policy.pap.main.rest.PapAafFilter;
55 import org.onap.policy.pap.main.rest.PapStatisticsManager;
56 import org.onap.policy.pap.main.rest.PdpGroupCreateOrUpdateControllerV1;
57 import org.onap.policy.pap.main.rest.PdpGroupDeleteControllerV1;
58 import org.onap.policy.pap.main.rest.PdpGroupDeployControllerV1;
59 import org.onap.policy.pap.main.rest.PdpGroupHealthCheckControllerV1;
60 import org.onap.policy.pap.main.rest.PdpGroupQueryControllerV1;
61 import org.onap.policy.pap.main.rest.PdpGroupStateChangeControllerV1;
62 import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckControllerV1;
63 import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckProvider;
64 import org.onap.policy.pap.main.rest.PolicyStatusControllerV1;
65 import org.onap.policy.pap.main.rest.PolicyUndeployerImpl;
66 import org.onap.policy.pap.main.rest.StatisticsRestControllerV1;
67
68 /**
69  * This class activates Policy Administration (PAP) as a complete service together with all its controllers, listeners &
70  * handlers.
71  *
72  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
73  */
74 public class PapActivator extends ServiceManagerContainer {
75     private static final String[] MSG_TYPE_NAMES = { "messageName" };
76     private static final String[] REQ_ID_NAMES = { "response", "responseTo" };
77
78     /**
79      * Max number of heat beats that can be missed before PAP removes a PDP.
80      */
81     private static final int MAX_MISSED_HEARTBEATS = 3;
82
83     private final PapParameterGroup papParameterGroup;
84
85     /**
86      * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then dispatches them to
87      * {@link #reqIdDispatcher}.
88      */
89     private final MessageTypeDispatcher msgDispatcher;
90
91     /**
92      * Listens for {@link PdpStatus} messages and then routes them to the listener associated with the ID of the
93      * originating request.
94      */
95     private final RequestIdDispatcher<PdpStatus> reqIdDispatcher;
96
97     /**
98      * Listener for anonymous {@link PdpStatus} messages either for registration or heartbeat.
99      */
100     private final PdpHeartbeatListener pdpHeartbeatListener;
101
102     /**
103      * Instantiate the activator for policy pap as a complete service.
104      *
105      * @param papParameterGroup the parameters for the pap service
106      */
107     public PapActivator(final PapParameterGroup papParameterGroup) {
108         super("Policy PAP");
109
110         TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup());
111
112         try {
113             this.papParameterGroup = papParameterGroup;
114             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
115             this.reqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
116             this.pdpHeartbeatListener = new PdpHeartbeatListener(papParameterGroup.getPdpParameters(),
117                             papParameterGroup.isSavePdpStatisticsInDb());
118
119         } catch (final RuntimeException e) {
120             throw new PolicyPapRuntimeException(e);
121         }
122
123         papParameterGroup.getRestServerParameters().setName(papParameterGroup.getName());
124
125         final var pdpUpdateLock = new Object();
126         final var pdpParams = papParameterGroup.getPdpParameters();
127         final AtomicReference<Publisher<PdpMessage>> pdpPub = new AtomicReference<>();
128         final AtomicReference<Publisher<PolicyNotification>> notifyPub = new AtomicReference<>();
129         final AtomicReference<TimerManager> pdpUpdTimers = new AtomicReference<>();
130         final AtomicReference<TimerManager> pdpStChgTimers = new AtomicReference<>();
131         final AtomicReference<ScheduledExecutorService> pdpExpirationTimer = new AtomicReference<>();
132         final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>();
133         final AtomicReference<PdpModifyRequestMap> requestMap = new AtomicReference<>();
134         final AtomicReference<RestServer> restServer = new AtomicReference<>();
135         final AtomicReference<PolicyNotifier> notifier = new AtomicReference<>();
136
137         // @formatter:off
138         addAction("PAP parameters",
139             () -> ParameterService.register(papParameterGroup),
140             () -> ParameterService.deregister(papParameterGroup.getName()));
141
142         addAction("DAO Factory",
143             () -> daoFactory.set(new PolicyModelsProviderFactoryWrapper(
144                                     papParameterGroup.getDatabaseProviderParameters())),
145             () -> daoFactory.get().close());
146
147         addAction("DAO Factory registration",
148             () -> Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daoFactory.get()),
149             () -> Registry.unregister(PapConstants.REG_PAP_DAO_FACTORY));
150
151         addAction("Pdp Heartbeat Listener",
152             () -> reqIdDispatcher.register(pdpHeartbeatListener),
153             () -> reqIdDispatcher.unregister(pdpHeartbeatListener));
154
155         addAction("Request ID Dispatcher",
156             () -> msgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.reqIdDispatcher),
157             () -> msgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
158
159         addAction("Message Dispatcher",
160             this::registerMsgDispatcher,
161             this::unregisterMsgDispatcher);
162
163         addAction("topics",
164             TopicEndpointManager.getManager()::start,
165             TopicEndpointManager.getManager()::shutdown);
166
167         addAction("PAP statistics",
168             () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
169             () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
170
171         addAction("PDP publisher",
172             () -> {
173                 pdpPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_PDP_PAP));
174                 startThread(pdpPub.get());
175             },
176             () -> pdpPub.get().stop());
177
178         addAction("Policy Notification publisher",
179             () -> {
180                 notifyPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_NOTIFICATION));
181                 startThread(notifyPub.get());
182                 notifier.set(new PolicyNotifier(notifyPub.get(), daoFactory.get()));
183             },
184             () -> notifyPub.get().stop());
185
186         addAction("Policy Notifier",
187             () -> Registry.register(PapConstants.REG_POLICY_NOTIFIER, notifier.get()),
188             () -> Registry.unregister(PapConstants.REG_POLICY_NOTIFIER));
189
190         addAction("PDP update timers",
191             () -> {
192                 pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs()));
193                 startThread(pdpUpdTimers.get());
194             },
195             () -> pdpUpdTimers.get().stop());
196
197         addAction("PDP state-change timers",
198             () -> {
199                 pdpStChgTimers.set(new TimerManager("state-change", pdpParams.getUpdateParameters().getMaxWaitMs()));
200                 startThread(pdpStChgTimers.get());
201             },
202             () -> pdpStChgTimers.get().stop());
203
204         addAction("PDP modification lock",
205             () -> Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, pdpUpdateLock),
206             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_LOCK));
207
208         addAction("PDP modification requests",
209             () -> {
210                 requestMap.set(new PdpModifyRequestMap(
211                             PdpModifyRequestMapParams.builder()
212                                     .maxPdpAgeMs(MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs())
213                                     .daoFactory(daoFactory.get())
214                                     .modifyLock(pdpUpdateLock)
215                                     .params(pdpParams)
216                                     .policyNotifier(notifier.get())
217                                     .pdpPublisher(pdpPub.get())
218                                     .responseDispatcher(reqIdDispatcher)
219                                     .stateChangeTimers(pdpStChgTimers.get())
220                                     .updateTimers(pdpUpdTimers.get())
221                                     .savePdpStatistics(papParameterGroup.isSavePdpStatisticsInDb())
222                                     .build()));
223                 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
224
225                 // now that it's registered, we can attach a "policy undeploy" provider
226                 requestMap.get().setPolicyUndeployer(new PolicyUndeployerImpl());
227             },
228             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
229
230         addAction("PDP expiration timer",
231             () -> {
232                 long frequencyMs = pdpParams.getHeartBeatMs();
233                 pdpExpirationTimer.set(Executors.newScheduledThreadPool(1));
234                 pdpExpirationTimer.get().scheduleWithFixedDelay(
235                     requestMap.get()::removeExpiredPdps,
236                     frequencyMs,
237                     frequencyMs,
238                     TimeUnit.MILLISECONDS);
239             },
240             () -> pdpExpirationTimer.get().shutdown());
241
242         addAction("PAP client executor",
243             () ->
244                 PolicyComponentsHealthCheckProvider.initializeClientHealthCheckExecutorService(papParameterGroup,
245                                 HttpClientFactoryInstance.getClientFactory()),
246                 PolicyComponentsHealthCheckProvider::cleanup);
247
248         addAction("REST server",
249             () -> {
250                 var server = new RestServer(papParameterGroup.getRestServerParameters(), PapAafFilter.class,
251                                 HealthCheckRestControllerV1.class,
252                                 StatisticsRestControllerV1.class,
253                                 PdpGroupCreateOrUpdateControllerV1.class,
254                                 PdpGroupDeployControllerV1.class,
255                                 PdpGroupDeleteControllerV1.class,
256                                 PdpGroupStateChangeControllerV1.class,
257                                 PdpGroupQueryControllerV1.class,
258                                 PdpGroupHealthCheckControllerV1.class,
259                                 PolicyStatusControllerV1.class,
260                                 PolicyComponentsHealthCheckControllerV1.class);
261                 restServer.set(server);
262                 restServer.get().start();
263             },
264             () -> restServer.get().stop());
265         // @formatter:on
266     }
267
268     /**
269      * Starts a background thread.
270      *
271      * @param runner function to run in the background
272      */
273     private void startThread(final Runnable runner) {
274         final var thread = new Thread(runner);
275         thread.setDaemon(true);
276
277         thread.start();
278     }
279
280     /**
281      * Get the parameters used by the activator.
282      *
283      * @return the parameters of the activator
284      */
285     public PapParameterGroup getParameterGroup() {
286         return papParameterGroup;
287     }
288
289     /**
290      * Registers the dispatcher with the topic source(s).
291      */
292     private void registerMsgDispatcher() {
293         for (final TopicSource source : TopicEndpointManager.getManager()
294                 .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
295             source.register(msgDispatcher);
296         }
297     }
298
299     /**
300      * Unregisters the dispatcher from the topic source(s).
301      */
302     private void unregisterMsgDispatcher() {
303         for (final TopicSource source : TopicEndpointManager.getManager()
304                 .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
305             source.unregister(msgDispatcher);
306         }
307     }
308 }