Allow xacml-pdp to use kafka
[policy/xacml-pdp.git] / main / src / main / java / org / onap / policy / pdpx / main / startstop / XacmlPdpActivator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
4  * Modifications Copyright (C) 2023 Nordix Foundation.
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.pdpx.main.startstop;
23
24 import java.util.List;
25 import lombok.Getter;
26 import lombok.Setter;
27 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
28 import org.onap.policy.common.endpoints.event.comm.client.BidirectionalTopicClient;
29 import org.onap.policy.common.endpoints.event.comm.client.BidirectionalTopicClientException;
30 import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient;
31 import org.onap.policy.common.endpoints.http.client.HttpClient;
32 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
33 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
34 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
35 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
36 import org.onap.policy.common.parameters.ParameterService;
37 import org.onap.policy.common.utils.services.ServiceManagerContainer;
38 import org.onap.policy.models.pdp.concepts.PdpStatus;
39 import org.onap.policy.models.pdp.enums.PdpMessageType;
40 import org.onap.policy.pdpx.main.PolicyXacmlPdpRuntimeException;
41 import org.onap.policy.pdpx.main.XacmlState;
42 import org.onap.policy.pdpx.main.comm.XacmlPdpHearbeatPublisher;
43 import org.onap.policy.pdpx.main.comm.listeners.XacmlPdpStateChangeListener;
44 import org.onap.policy.pdpx.main.comm.listeners.XacmlPdpUpdateListener;
45 import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup;
46 import org.onap.policy.pdpx.main.rest.XacmlPdpApplicationManager;
47 import org.onap.policy.pdpx.main.rest.XacmlPdpRestController;
48 import org.onap.policy.pdpx.main.rest.XacmlPdpServiceFilter;
49 import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * This class wraps a distributor so that it can be activated as a complete service together with
55  * all its xacml pdp and forwarding handlers.
56  */
57 public class XacmlPdpActivator extends ServiceManagerContainer {
58
59     // The logger for this class
60     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpActivator.class);
61
62     private static final String[] MSG_TYPE_NAMES = {"messageName"};
63     private static final String TOPIC = "policy-pdp-pap";
64
65     @Getter
66     @Setter
67     private static XacmlPdpActivator current = null;
68
69     // The parameters of this policy xacml pdp activator
70     private final XacmlPdpParameterGroup xacmlPdpParameterGroup;
71
72     /**
73      * POLICY-PDP-PAP client.
74      */
75     private final BidirectionalTopicClient topicClient;
76
77     /**
78      * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then
79      * dispatches them to appropriate listener.
80      */
81     private final MessageTypeDispatcher msgDispatcher;
82
83     /**
84      * Instantiate the activator for policy xacml pdp as a complete service.
85      *
86      * @param xacmlPdpParameterGroup the parameters for the xacml pdp service
87      */
88     public XacmlPdpActivator(final XacmlPdpParameterGroup xacmlPdpParameterGroup) {
89         LOGGER.info("Activator initializing using {}", xacmlPdpParameterGroup);
90
91         RestClientParameters apiClientParams = xacmlPdpParameterGroup.getPolicyApiParameters();
92
93         TopicEndpointManager.getManager().addTopics(xacmlPdpParameterGroup.getTopicParameterGroup());
94
95         final XacmlPdpHearbeatPublisher heartbeat;
96         final TopicSinkClient sinkClient;
97         final XacmlState state;
98
99         XacmlPdpRestServer restServer;
100         try {
101             HttpClient apiClient = HttpClientFactoryInstance.getClientFactory().build(apiClientParams);
102
103             var appmgr = new XacmlPdpApplicationManager(xacmlPdpParameterGroup.getApplicationParameters(),
104                                             apiClient);
105             XacmlPdpApplicationManager.setCurrent(appmgr);
106
107             var stats = new XacmlPdpStatisticsManager();
108             XacmlPdpStatisticsManager.setCurrent(stats);
109             stats.setTotalPolicyTypesCount(appmgr.getPolicyTypeCount());
110             stats.setTotalPolicyCount(appmgr.getPolicyCount());
111
112             state = new XacmlState(appmgr, xacmlPdpParameterGroup.getPdpGroup(), xacmlPdpParameterGroup.getPdpType());
113
114             this.xacmlPdpParameterGroup = xacmlPdpParameterGroup;
115             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
116
117             topicClient = new BidirectionalTopicClient(TOPIC, TOPIC);
118             sinkClient = new TopicSinkClient(topicClient.getSink());
119
120             heartbeat = new XacmlPdpHearbeatPublisher(topicClient,
121                             xacmlPdpParameterGroup.getProbeHeartbeatTopicSec() * 1000, state);
122
123             /*
124              * since the dispatcher isn't registered with the topic yet, we can go ahead
125              * and register the listeners with it.
126              */
127             msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(),
128                             new XacmlPdpStateChangeListener(sinkClient, state));
129             msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(),
130                             new XacmlPdpUpdateListener(sinkClient, state, heartbeat, appmgr));
131
132             XacmlPdpServiceFilter.disableApi();
133
134             restServer = new XacmlPdpRestServer(xacmlPdpParameterGroup.getRestServerParameters(),
135                                 List.of(XacmlPdpServiceFilter.class), List.of(XacmlPdpRestController.class));
136
137         } catch (RuntimeException | HttpClientConfigException | BidirectionalTopicClientException e) {
138             throw new PolicyXacmlPdpRuntimeException(e.getMessage(), e);
139         }
140
141         xacmlPdpParameterGroup.getRestServerParameters().setName(xacmlPdpParameterGroup.getName());
142
143         // @formatter:off
144         addAction("XACML PDP parameters",
145             () -> ParameterService.register(xacmlPdpParameterGroup),
146             () -> ParameterService.deregister(xacmlPdpParameterGroup.getName()));
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("Terminate PDP",
157             () -> { },
158             () -> sendTerminateMessage(sinkClient, state));
159         // initial heart beats act as registration messages
160         addAction("Heartbeat Publisher",
161             heartbeat::start,
162             heartbeat::terminate);
163
164         // @formatter:on
165         addAction("REST Server",
166             restServer::start,
167             restServer::stop);
168     }
169
170     /*
171      * Method used to send a terminate message to the PAP.
172      */
173     private void sendTerminateMessage(TopicSinkClient sinkClient, XacmlState state) {
174         PdpStatus terminateStatus = state.terminatePdpMessage();
175         sinkClient.send(terminateStatus);
176     }
177
178     /**
179      * Get the parameters used by the activator.
180      *
181      * @return the parameters of the activator
182      */
183     public XacmlPdpParameterGroup getParameterGroup() {
184         return xacmlPdpParameterGroup;
185     }
186
187     /**
188      * Method to register the parameters to Common Parameter Service.
189      *
190      * @param xacmlPdpParameterGroup the xacml pdp parameter group
191      */
192     public void registerToParameterService(final XacmlPdpParameterGroup xacmlPdpParameterGroup) {
193         ParameterService.register(xacmlPdpParameterGroup);
194     }
195
196     /**
197      * Method to deregister the parameters from Common Parameter Service.
198      *
199      * @param xacmlPdpParameterGroup the xacml pdp parameter group
200      */
201     public void deregisterToParameterService(final XacmlPdpParameterGroup xacmlPdpParameterGroup) {
202         ParameterService.deregister(xacmlPdpParameterGroup.getName());
203     }
204
205     /**
206      * Registers the dispatcher with the topic source(s).
207      */
208     private void registerMsgDispatcher() {
209         topicClient.getSource().register(msgDispatcher);
210     }
211
212     /**
213      * Unregisters the dispatcher from the topic source(s).
214      */
215     private void unregisterMsgDispatcher() {
216         topicClient.getSource().unregister(msgDispatcher);
217     }
218
219     /**
220      * Start the xacmlpdp rest controller.
221      */
222     public void enableApi() {
223         XacmlPdpServiceFilter.enableApi();
224     }
225
226     /**
227      * Stop the xacmlpdp rest controller.
228      */
229     public void disableApi() {
230         XacmlPdpServiceFilter.disableApi();
231     }
232
233     public boolean isApiEnabled() {
234         return XacmlPdpServiceFilter.isApiEnabled();
235     }
236 }