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