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