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