Merge "Parallel execution of Client Health check"
[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-2020 AT&T Intellectual Property.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pap.main.startstop;
23
24 import java.util.Arrays;
25 import java.util.concurrent.atomic.AtomicReference;
26 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
27 import org.onap.policy.common.endpoints.event.comm.TopicSource;
28 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
29 import org.onap.policy.common.endpoints.http.server.RestServer;
30 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
31 import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher;
32 import org.onap.policy.common.parameters.ParameterService;
33 import org.onap.policy.common.utils.services.Registry;
34 import org.onap.policy.common.utils.services.ServiceManagerContainer;
35 import org.onap.policy.models.pap.concepts.PolicyNotification;
36 import org.onap.policy.models.pdp.concepts.PdpMessage;
37 import org.onap.policy.models.pdp.concepts.PdpStatus;
38 import org.onap.policy.models.pdp.enums.PdpMessageType;
39 import org.onap.policy.pap.main.PapConstants;
40 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
41 import org.onap.policy.pap.main.PolicyPapRuntimeException;
42 import org.onap.policy.pap.main.comm.PdpHeartbeatListener;
43 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
44 import org.onap.policy.pap.main.comm.PdpTracker;
45 import org.onap.policy.pap.main.comm.Publisher;
46 import org.onap.policy.pap.main.comm.TimerManager;
47 import org.onap.policy.pap.main.notification.PolicyNotifier;
48 import org.onap.policy.pap.main.parameters.PapParameterGroup;
49 import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams;
50 import org.onap.policy.pap.main.parameters.PdpParameters;
51 import org.onap.policy.pap.main.rest.HealthCheckRestControllerV1;
52 import org.onap.policy.pap.main.rest.PapAafFilter;
53 import org.onap.policy.pap.main.rest.PapStatisticsManager;
54 import org.onap.policy.pap.main.rest.PdpGroupCreateOrUpdateControllerV1;
55 import org.onap.policy.pap.main.rest.PdpGroupDeleteControllerV1;
56 import org.onap.policy.pap.main.rest.PdpGroupDeployControllerV1;
57 import org.onap.policy.pap.main.rest.PdpGroupHealthCheckControllerV1;
58 import org.onap.policy.pap.main.rest.PdpGroupQueryControllerV1;
59 import org.onap.policy.pap.main.rest.PdpGroupStateChangeControllerV1;
60 import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckControllerV1;
61 import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckProvider;
62 import org.onap.policy.pap.main.rest.PolicyStatusControllerV1;
63 import org.onap.policy.pap.main.rest.PolicyUndeployerImpl;
64 import org.onap.policy.pap.main.rest.StatisticsRestControllerV1;
65
66 /**
67  * This class activates Policy Administration (PAP) as a complete service together with all its controllers, listeners &
68  * handlers.
69  *
70  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
71  */
72 public class PapActivator extends ServiceManagerContainer {
73     private static final String[] MSG_TYPE_NAMES = { "messageName" };
74     private static final String[] REQ_ID_NAMES = { "response", "responseTo" };
75
76     /**
77      * Max number of heat beats that can be missed before PAP removes a PDP.
78      */
79     private static final int MAX_MISSED_HEARTBEATS = 3;
80
81     private final PapParameterGroup papParameterGroup;
82
83     /**
84      * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then dispatches them to
85      * {@link #reqIdDispatcher}.
86      */
87     private final MessageTypeDispatcher msgDispatcher;
88
89     /**
90      * Listens for {@link PdpStatus} messages and then routes them to the listener associated with the ID of the
91      * originating request.
92      */
93     private final RequestIdDispatcher<PdpStatus> reqIdDispatcher;
94
95     /**
96      * Listener for anonymous {@link PdpStatus} messages either for registration or heartbeat.
97      */
98     private final PdpHeartbeatListener pdpHeartbeatListener;
99
100     /**
101      * Instantiate the activator for policy pap as a complete service.
102      *
103      * @param papParameterGroup the parameters for the pap service
104      */
105     public PapActivator(final PapParameterGroup papParameterGroup) {
106         super("Policy PAP");
107
108         TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup());
109
110         try {
111             this.papParameterGroup = papParameterGroup;
112             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
113             this.reqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
114             this.pdpHeartbeatListener = new PdpHeartbeatListener(papParameterGroup.getPdpParameters());
115
116         } catch (final RuntimeException e) {
117             throw new PolicyPapRuntimeException(e);
118         }
119
120         papParameterGroup.getRestServerParameters().setName(papParameterGroup.getName());
121
122         final Object pdpUpdateLock = new Object();
123         final PdpParameters pdpParams = papParameterGroup.getPdpParameters();
124         final AtomicReference<Publisher<PdpMessage>> pdpPub = new AtomicReference<>();
125         final AtomicReference<Publisher<PolicyNotification>> notifyPub = new AtomicReference<>();
126         final AtomicReference<TimerManager> pdpUpdTimers = new AtomicReference<>();
127         final AtomicReference<TimerManager> pdpStChgTimers = new AtomicReference<>();
128         final AtomicReference<TimerManager> heartBeatTimers = new AtomicReference<>();
129         final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>();
130         final AtomicReference<PdpModifyRequestMap> requestMap = new AtomicReference<>();
131         final AtomicReference<RestServer> restServer = new AtomicReference<>();
132         final AtomicReference<PolicyNotifier> notifier = new AtomicReference<>();
133
134         // @formatter:off
135         addAction("PAP parameters",
136             () -> ParameterService.register(papParameterGroup),
137             () -> ParameterService.deregister(papParameterGroup.getName()));
138
139         addAction("DAO Factory",
140             () -> daoFactory.set(new PolicyModelsProviderFactoryWrapper(
141                                     papParameterGroup.getDatabaseProviderParameters())),
142             () -> daoFactory.get().close());
143
144         addAction("DAO Factory registration",
145             () -> Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daoFactory.get()),
146             () -> Registry.unregister(PapConstants.REG_PAP_DAO_FACTORY));
147
148         addAction("Pdp Heartbeat Listener",
149             () -> reqIdDispatcher.register(pdpHeartbeatListener),
150             () -> reqIdDispatcher.unregister(pdpHeartbeatListener));
151
152         addAction("Request ID Dispatcher",
153             () -> msgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.reqIdDispatcher),
154             () -> msgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
155
156         addAction("Message Dispatcher",
157             this::registerMsgDispatcher,
158             this::unregisterMsgDispatcher);
159
160         addAction("topics",
161             TopicEndpointManager.getManager()::start,
162             TopicEndpointManager.getManager()::shutdown);
163
164         addAction("PAP statistics",
165             () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
166             () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
167
168         addAction("PDP publisher",
169             () -> {
170                 pdpPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_PDP_PAP));
171                 startThread(pdpPub.get());
172             },
173             () -> pdpPub.get().stop());
174
175         addAction("Policy Notification publisher",
176             () -> {
177                 notifyPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_NOTIFICATION));
178                 startThread(notifyPub.get());
179                 notifier.set(new PolicyNotifier(notifyPub.get(), daoFactory.get()));
180             },
181             () -> notifyPub.get().stop());
182
183         addAction("Policy Notifier",
184             () -> Registry.register(PapConstants.REG_POLICY_NOTIFIER, notifier.get()),
185             () -> Registry.unregister(PapConstants.REG_POLICY_NOTIFIER));
186
187         addAction("PDP heart beat timers",
188             () -> {
189                 long maxWaitHeartBeatMs = MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs();
190                 heartBeatTimers.set(new TimerManager("heart beat", maxWaitHeartBeatMs));
191                 startThread(heartBeatTimers.get());
192             },
193             () -> heartBeatTimers.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                 requestMap.set(new PdpModifyRequestMap(
216                             new PdpModifyRequestMapParams()
217                                     .setDaoFactory(daoFactory.get())
218                                     .setModifyLock(pdpUpdateLock)
219                                     .setParams(pdpParams)
220                                     .setPolicyNotifier(notifier.get())
221                                     .setPdpPublisher(pdpPub.get())
222                                     .setResponseDispatcher(reqIdDispatcher)
223                                     .setStateChangeTimers(pdpStChgTimers.get())
224                                     .setUpdateTimers(pdpUpdTimers.get())));
225                 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
226
227                 // now that it's registered, we can attach a "policy undeploy" provider
228                 requestMap.get().setPolicyUndeployer(new PolicyUndeployerImpl());
229             },
230             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
231
232         addAction("PDP heart beat tracker",
233             () -> Registry.register(PapConstants.REG_PDP_TRACKER, PdpTracker.builder()
234                                     .daoFactory(daoFactory.get())
235                                     .timers(heartBeatTimers.get())
236                                     .modifyLock(pdpUpdateLock)
237                                     .requestMap(requestMap.get())
238                                     .build()),
239             () -> Registry.unregister(PapConstants.REG_PDP_TRACKER));
240
241         addAction("PAP client executor",
242             () ->
243                 PolicyComponentsHealthCheckProvider.initializeClientHealthCheckExecutorService(papParameterGroup,
244                                 HttpClientFactoryInstance.getClientFactory()),
245                 PolicyComponentsHealthCheckProvider::cleanup);
246
247         addAction("REST server",
248             () -> {
249                 RestServer server = new RestServer(papParameterGroup.getRestServerParameters(), PapAafFilter.class,
250                                 HealthCheckRestControllerV1.class,
251                                 StatisticsRestControllerV1.class,
252                                 PdpGroupCreateOrUpdateControllerV1.class,
253                                 PdpGroupDeployControllerV1.class,
254                                 PdpGroupDeleteControllerV1.class,
255                                 PdpGroupStateChangeControllerV1.class,
256                                 PdpGroupQueryControllerV1.class,
257                                 PdpGroupHealthCheckControllerV1.class,
258                                 PolicyStatusControllerV1.class,
259                                 PolicyComponentsHealthCheckControllerV1.class);
260                 restServer.set(server);
261                 restServer.get().start();
262             },
263             () -> restServer.get().stop());
264         // @formatter:on
265     }
266
267     /**
268      * Starts a background thread.
269      *
270      * @param runner function to run in the background
271      */
272     private void startThread(final Runnable runner) {
273         final Thread thread = new Thread(runner);
274         thread.setDaemon(true);
275
276         thread.start();
277     }
278
279     /**
280      * Get the parameters used by the activator.
281      *
282      * @return the parameters of the activator
283      */
284     public PapParameterGroup getParameterGroup() {
285         return papParameterGroup;
286     }
287
288     /**
289      * Registers the dispatcher with the topic source(s).
290      */
291     private void registerMsgDispatcher() {
292         for (final TopicSource source : TopicEndpointManager.getManager()
293                 .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
294             source.register(msgDispatcher);
295         }
296     }
297
298     /**
299      * Unregisters the dispatcher from the topic source(s).
300      */
301     private void unregisterMsgDispatcher() {
302         for (final TopicSource source : TopicEndpointManager.getManager()
303                 .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
304             source.unregister(msgDispatcher);
305         }
306     }
307 }