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