Add apis for policy audit
[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  *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.startstop;
24
25 import java.util.List;
26 import java.util.concurrent.Executors;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.atomic.AtomicReference;
30 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
31 import org.onap.policy.common.endpoints.event.comm.TopicListener;
32 import org.onap.policy.common.endpoints.event.comm.TopicSource;
33 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
34 import org.onap.policy.common.endpoints.http.server.RestServer;
35 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
36 import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher;
37 import org.onap.policy.common.parameters.ParameterService;
38 import org.onap.policy.common.utils.services.Registry;
39 import org.onap.policy.common.utils.services.ServiceManagerContainer;
40 import org.onap.policy.models.pap.concepts.PolicyNotification;
41 import org.onap.policy.models.pdp.concepts.PdpMessage;
42 import org.onap.policy.models.pdp.concepts.PdpStatus;
43 import org.onap.policy.models.pdp.enums.PdpMessageType;
44 import org.onap.policy.pap.main.PapConstants;
45 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
46 import org.onap.policy.pap.main.PolicyPapRuntimeException;
47 import org.onap.policy.pap.main.comm.PdpHeartbeatListener;
48 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
49 import org.onap.policy.pap.main.comm.Publisher;
50 import org.onap.policy.pap.main.comm.TimerManager;
51 import org.onap.policy.pap.main.notification.PolicyNotifier;
52 import org.onap.policy.pap.main.parameters.PapParameterGroup;
53 import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams;
54 import org.onap.policy.pap.main.rest.HealthCheckRestControllerV1;
55 import org.onap.policy.pap.main.rest.PapAafFilter;
56 import org.onap.policy.pap.main.rest.PapStatisticsManager;
57 import org.onap.policy.pap.main.rest.PdpGroupCreateOrUpdateControllerV1;
58 import org.onap.policy.pap.main.rest.PdpGroupDeleteControllerV1;
59 import org.onap.policy.pap.main.rest.PdpGroupDeployControllerV1;
60 import org.onap.policy.pap.main.rest.PdpGroupHealthCheckControllerV1;
61 import org.onap.policy.pap.main.rest.PdpGroupQueryControllerV1;
62 import org.onap.policy.pap.main.rest.PdpGroupStateChangeControllerV1;
63 import org.onap.policy.pap.main.rest.PolicyAuditControllerV1;
64 import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckControllerV1;
65 import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckProvider;
66 import org.onap.policy.pap.main.rest.PolicyStatusControllerV1;
67 import org.onap.policy.pap.main.rest.PolicyUndeployerImpl;
68 import org.onap.policy.pap.main.rest.StatisticsRestControllerV1;
69
70 /**
71  * This class activates Policy Administration (PAP) as a complete service together with all its controllers, listeners &
72  * handlers.
73  *
74  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
75  */
76 public class PapActivator extends ServiceManagerContainer {
77     private static final String[] MSG_TYPE_NAMES = { "messageName" };
78     private static final String[] REQ_ID_NAMES = { "response", "responseTo" };
79
80     /**
81      * Max number of heat beats that can be missed before PAP removes a PDP.
82      */
83     private static final int MAX_MISSED_HEARTBEATS = 3;
84
85     private final PapParameterGroup papParameterGroup;
86
87     /**
88      * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then dispatches them to
89      * {@link #responseReqIdDispatcher}.
90      */
91     private final MessageTypeDispatcher responseMsgDispatcher;
92     private final MessageTypeDispatcher heartbeatMsgDispatcher;
93
94     /**
95      * Listens for {@link PdpStatus} messages and then routes them to the listener associated with the ID of the
96      * originating request.
97      */
98     private final RequestIdDispatcher<PdpStatus> responseReqIdDispatcher;
99     private final RequestIdDispatcher<PdpStatus> heartbeatReqIdDispatcher;
100
101     /**
102      * Listener for anonymous {@link PdpStatus} messages either for registration or heartbeat.
103      */
104     private final PdpHeartbeatListener pdpHeartbeatListener;
105
106     /**
107      * Instantiate the activator for policy pap as a complete service.
108      *
109      * @param papParameterGroup the parameters for the pap service
110      */
111     public PapActivator(final PapParameterGroup papParameterGroup) {
112         super("Policy PAP");
113
114         TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup());
115
116         try {
117             this.papParameterGroup = papParameterGroup;
118             this.responseMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
119             this.heartbeatMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
120             this.responseReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
121             this.heartbeatReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
122             this.pdpHeartbeatListener = new PdpHeartbeatListener(papParameterGroup.getPdpParameters(),
123                             papParameterGroup.isSavePdpStatisticsInDb());
124
125         } catch (final RuntimeException e) {
126             throw new PolicyPapRuntimeException(e);
127         }
128
129         papParameterGroup.getRestServerParameters().setName(papParameterGroup.getName());
130
131         final var pdpUpdateLock = new Object();
132         final var pdpParams = papParameterGroup.getPdpParameters();
133         final AtomicReference<Publisher<PdpMessage>> pdpPub = new AtomicReference<>();
134         final AtomicReference<Publisher<PolicyNotification>> notifyPub = new AtomicReference<>();
135         final AtomicReference<TimerManager> pdpUpdTimers = new AtomicReference<>();
136         final AtomicReference<TimerManager> pdpStChgTimers = new AtomicReference<>();
137         final AtomicReference<ScheduledExecutorService> pdpExpirationTimer = new AtomicReference<>();
138         final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>();
139         final AtomicReference<PdpModifyRequestMap> requestMap = new AtomicReference<>();
140         final AtomicReference<RestServer> restServer = new AtomicReference<>();
141         final AtomicReference<PolicyNotifier> notifier = new AtomicReference<>();
142
143         // @formatter:off
144         addAction("PAP parameters",
145             () -> ParameterService.register(papParameterGroup),
146             () -> ParameterService.deregister(papParameterGroup.getName()));
147
148         addAction("DAO Factory",
149             () -> daoFactory.set(new PolicyModelsProviderFactoryWrapper(
150                                     papParameterGroup.getDatabaseProviderParameters())),
151             () -> daoFactory.get().close());
152
153         addAction("DAO Factory registration",
154             () -> Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daoFactory.get()),
155             () -> Registry.unregister(PapConstants.REG_PAP_DAO_FACTORY));
156
157         addAction("Pdp Heartbeat Listener",
158             () -> heartbeatReqIdDispatcher.register(pdpHeartbeatListener),
159             () -> heartbeatReqIdDispatcher.unregister(pdpHeartbeatListener));
160
161         addAction("Response Request ID Dispatcher",
162             () -> responseMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.responseReqIdDispatcher),
163             () -> responseMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
164
165         addAction("Heartbeat Request ID Dispatcher",
166             () -> heartbeatMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.heartbeatReqIdDispatcher),
167             () -> heartbeatMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
168
169         addAction("Response Message Dispatcher",
170             () -> registerMsgDispatcher(responseMsgDispatcher, PapConstants.TOPIC_POLICY_PDP_PAP),
171             () -> unregisterMsgDispatcher(responseMsgDispatcher, PapConstants.TOPIC_POLICY_PDP_PAP));
172
173         addAction("Heartbeat Message Dispatcher",
174             () -> registerMsgDispatcher(heartbeatMsgDispatcher, PapConstants.TOPIC_POLICY_HEARTBEAT),
175             () -> unregisterMsgDispatcher(heartbeatMsgDispatcher, PapConstants.TOPIC_POLICY_HEARTBEAT));
176
177         addAction("topics",
178             TopicEndpointManager.getManager()::start,
179             TopicEndpointManager.getManager()::shutdown);
180
181         addAction("PAP statistics",
182             () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
183             () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
184
185         addAction("PDP publisher",
186             () -> {
187                 pdpPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_PDP_PAP));
188                 startThread(pdpPub.get());
189             },
190             () -> pdpPub.get().stop());
191
192         addAction("Policy Notification publisher",
193             () -> {
194                 notifyPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_NOTIFICATION));
195                 startThread(notifyPub.get());
196                 notifier.set(new PolicyNotifier(notifyPub.get(), daoFactory.get()));
197             },
198             () -> notifyPub.get().stop());
199
200         addAction("Policy Notifier",
201             () -> Registry.register(PapConstants.REG_POLICY_NOTIFIER, notifier.get()),
202             () -> Registry.unregister(PapConstants.REG_POLICY_NOTIFIER));
203
204         addAction("PDP update timers",
205             () -> {
206                 pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs()));
207                 startThread(pdpUpdTimers.get());
208             },
209             () -> pdpUpdTimers.get().stop());
210
211         addAction("PDP state-change timers",
212             () -> {
213                 pdpStChgTimers.set(new TimerManager("state-change", pdpParams.getUpdateParameters().getMaxWaitMs()));
214                 startThread(pdpStChgTimers.get());
215             },
216             () -> pdpStChgTimers.get().stop());
217
218         addAction("PDP modification lock",
219             () -> Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, pdpUpdateLock),
220             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_LOCK));
221
222         addAction("PDP modification requests",
223             () -> {
224                 requestMap.set(new PdpModifyRequestMap(
225                             PdpModifyRequestMapParams.builder()
226                                     .maxPdpAgeMs(MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs())
227                                     .daoFactory(daoFactory.get())
228                                     .modifyLock(pdpUpdateLock)
229                                     .params(pdpParams)
230                                     .policyNotifier(notifier.get())
231                                     .pdpPublisher(pdpPub.get())
232                                     .responseDispatcher(responseReqIdDispatcher)
233                                     .stateChangeTimers(pdpStChgTimers.get())
234                                     .updateTimers(pdpUpdTimers.get())
235                                     .savePdpStatistics(papParameterGroup.isSavePdpStatisticsInDb())
236                                     .build()));
237                 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
238
239                 // now that it's registered, we can attach a "policy undeploy" provider
240                 requestMap.get().setPolicyUndeployer(new PolicyUndeployerImpl());
241             },
242             () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP));
243
244         addAction("PDP expiration timer",
245             () -> {
246                 long frequencyMs = pdpParams.getHeartBeatMs();
247                 pdpExpirationTimer.set(Executors.newScheduledThreadPool(1));
248                 pdpExpirationTimer.get().scheduleWithFixedDelay(
249                     requestMap.get()::removeExpiredPdps,
250                     frequencyMs,
251                     frequencyMs,
252                     TimeUnit.MILLISECONDS);
253             },
254             () -> pdpExpirationTimer.get().shutdown());
255
256         addAction("PAP client executor",
257             () ->
258                 PolicyComponentsHealthCheckProvider.initializeClientHealthCheckExecutorService(papParameterGroup,
259                                 HttpClientFactoryInstance.getClientFactory()),
260                 PolicyComponentsHealthCheckProvider::cleanup);
261
262         addAction("REST server",
263             () -> {
264                 var server = new RestServer(papParameterGroup.getRestServerParameters(), PapAafFilter.class,
265                                 HealthCheckRestControllerV1.class,
266                                 StatisticsRestControllerV1.class,
267                                 PdpGroupCreateOrUpdateControllerV1.class,
268                                 PdpGroupDeployControllerV1.class,
269                                 PdpGroupDeleteControllerV1.class,
270                                 PdpGroupStateChangeControllerV1.class,
271                                 PdpGroupQueryControllerV1.class,
272                                 PdpGroupHealthCheckControllerV1.class,
273                                 PolicyStatusControllerV1.class,
274                                 PolicyComponentsHealthCheckControllerV1.class,
275                                 PolicyAuditControllerV1.class);
276                 restServer.set(server);
277                 restServer.get().start();
278             },
279             () -> restServer.get().stop());
280         // @formatter:on
281     }
282
283     /**
284      * Starts a background thread.
285      *
286      * @param runner function to run in the background
287      */
288     private void startThread(final Runnable runner) {
289         final var thread = new Thread(runner);
290         thread.setDaemon(true);
291
292         thread.start();
293     }
294
295     /**
296      * Get the parameters used by the activator.
297      *
298      * @return the parameters of the activator
299      */
300     public PapParameterGroup getParameterGroup() {
301         return papParameterGroup;
302     }
303
304     /**
305      * Registers the dispatcher with the topic source(s).
306      * @param dispatcher dispatcher to register
307      * @param topic topic of interest
308      */
309     private void registerMsgDispatcher(TopicListener dispatcher, String topic) {
310         for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
311             source.register(dispatcher);
312         }
313     }
314
315     /**
316      * Unregisters the dispatcher from the topic source(s).
317      * @param dispatcher dispatcher to unregister
318      * @param topic topic of interest
319      */
320     private void unregisterMsgDispatcher(TopicListener dispatcher, String topic) {
321         for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
322             source.unregister(dispatcher);
323         }
324     }
325 }