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