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