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