e74ab9bf5e6f5d30c3c73facbf756e621f737ea4
[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  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pdpx.main.startstop;
22
23 import java.util.Arrays;
24 import lombok.Getter;
25 import lombok.Setter;
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.event.comm.client.TopicSinkClient;
29 import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClientException;
30 import org.onap.policy.common.endpoints.http.client.HttpClient;
31 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
32 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
33 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
34 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
35 import org.onap.policy.common.parameters.ParameterService;
36 import org.onap.policy.common.utils.services.ServiceManagerContainer;
37 import org.onap.policy.models.pdp.concepts.PdpStatus;
38 import org.onap.policy.models.pdp.enums.PdpMessageType;
39 import org.onap.policy.pdpx.main.PolicyXacmlPdpRuntimeException;
40 import org.onap.policy.pdpx.main.XacmlState;
41 import org.onap.policy.pdpx.main.comm.XacmlPdpHearbeatPublisher;
42 import org.onap.policy.pdpx.main.comm.listeners.XacmlPdpStateChangeListener;
43 import org.onap.policy.pdpx.main.comm.listeners.XacmlPdpUpdateListener;
44 import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup;
45 import org.onap.policy.pdpx.main.rest.XacmlPdpAafFilter;
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.XacmlPdpStatisticsManager;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * This class wraps a distributor so that it can be activated as a complete service together with
54  * all its xacml pdp and forwarding handlers.
55  */
56 public class XacmlPdpActivator extends ServiceManagerContainer {
57
58     // The logger for this class
59     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpActivator.class);
60
61     private static final String[] MSG_TYPE_NAMES = {"messageName"};
62     private static final String TOPIC = "POLICY-PDP-PAP";
63
64     @Getter
65     @Setter
66     private static XacmlPdpActivator current = null;
67     private final XacmlPdpRestServer restServer;
68
69     // The parameters of this policy xacml pdp activator
70     private final XacmlPdpParameterGroup xacmlPdpParameterGroup;
71
72     /**
73      * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then
74      * dispatches them to appropriate listener.
75      */
76     private final MessageTypeDispatcher msgDispatcher;
77
78     /**
79      * Instantiate the activator for policy xacml pdp as a complete service.
80      *
81      * @param xacmlPdpParameterGroup the parameters for the xacml pdp service
82      */
83     public XacmlPdpActivator(final XacmlPdpParameterGroup xacmlPdpParameterGroup) {
84         LOGGER.info("Activator initializing using {}", xacmlPdpParameterGroup);
85
86         RestClientParameters apiClientParams = xacmlPdpParameterGroup.getPolicyApiParameters();
87
88         TopicEndpointManager.getManager().addTopics(xacmlPdpParameterGroup.getTopicParameterGroup());
89
90         final XacmlPdpHearbeatPublisher heartbeat;
91         final TopicSinkClient sinkClient;
92         final XacmlState state;
93
94         try {
95             HttpClient apiClient = HttpClientFactoryInstance.getClientFactory().build(apiClientParams);
96
97             var appmgr = new XacmlPdpApplicationManager(xacmlPdpParameterGroup.getApplicationParameters(),
98                                             apiClient);
99             XacmlPdpApplicationManager.setCurrent(appmgr);
100
101             var stats = new XacmlPdpStatisticsManager();
102             XacmlPdpStatisticsManager.setCurrent(stats);
103             stats.setTotalPolicyTypesCount(appmgr.getPolicyTypeCount());
104             stats.setTotalPolicyCount(appmgr.getPolicyCount());
105
106             state = new XacmlState(appmgr, xacmlPdpParameterGroup.getPdpGroup(), xacmlPdpParameterGroup.getPdpType());
107
108             this.xacmlPdpParameterGroup = xacmlPdpParameterGroup;
109             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
110
111             sinkClient = new TopicSinkClient(TOPIC);
112             heartbeat = new XacmlPdpHearbeatPublisher(sinkClient, state);
113
114             /*
115              * since the dispatcher isn't registered with the topic yet, we can go ahead
116              * and register the listeners with it.
117              */
118             msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(),
119                             new XacmlPdpStateChangeListener(sinkClient, state));
120             msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(),
121                             new XacmlPdpUpdateListener(sinkClient, state, heartbeat, appmgr));
122
123             restServer = new XacmlPdpRestServer(xacmlPdpParameterGroup.getRestServerParameters(),
124                     XacmlPdpAafFilter.class, XacmlPdpRestController.class);
125
126         } catch (RuntimeException | TopicSinkClientException | HttpClientConfigException e) {
127             throw new PolicyXacmlPdpRuntimeException(e.getMessage(), e);
128         }
129
130         xacmlPdpParameterGroup.getRestServerParameters().setName(xacmlPdpParameterGroup.getName());
131
132         // @formatter:off
133         addAction("XACML PDP parameters",
134             () -> ParameterService.register(xacmlPdpParameterGroup),
135             () -> ParameterService.deregister(xacmlPdpParameterGroup.getName()));
136
137         addAction("Message Dispatcher",
138             this::registerMsgDispatcher,
139             this::unregisterMsgDispatcher);
140
141         addAction("topics",
142             TopicEndpointManager.getManager()::start,
143             TopicEndpointManager.getManager()::shutdown);
144
145         addAction("Terminate PDP",
146             () -> { },
147             () -> sendTerminateMessage(sinkClient, state));
148         // initial heart beats act as registration messages
149         addAction("Heartbeat Publisher",
150             heartbeat::start,
151             heartbeat::terminate);
152
153         // @formatter:on
154     }
155
156     /*
157      * Method used to send a terminate message to the PAP.
158      */
159     private void sendTerminateMessage(TopicSinkClient sinkClient, XacmlState state) {
160         PdpStatus terminateStatus = state.terminatePdpMessage();
161         sinkClient.send(terminateStatus);
162     }
163
164     /**
165      * Get the parameters used by the activator.
166      *
167      * @return the parameters of the activator
168      */
169     public XacmlPdpParameterGroup getParameterGroup() {
170         return xacmlPdpParameterGroup;
171     }
172
173     /**
174      * Method to register the parameters to Common Parameter Service.
175      *
176      * @param xacmlPdpParameterGroup the xacml pdp parameter group
177      */
178     public void registerToParameterService(final XacmlPdpParameterGroup xacmlPdpParameterGroup) {
179         ParameterService.register(xacmlPdpParameterGroup);
180     }
181
182     /**
183      * Method to deregister the parameters from Common Parameter Service.
184      *
185      * @param xacmlPdpParameterGroup the xacml pdp parameter group
186      */
187     public void deregisterToParameterService(final XacmlPdpParameterGroup xacmlPdpParameterGroup) {
188         ParameterService.deregister(xacmlPdpParameterGroup.getName());
189     }
190
191     /**
192      * Registers the dispatcher with the topic source(s).
193      */
194     private void registerMsgDispatcher() {
195         for (TopicSource source : TopicEndpointManager.getManager().getTopicSources(Arrays.asList(TOPIC))) {
196             source.register(msgDispatcher);
197         }
198     }
199
200     /**
201      * Unregisters the dispatcher from the topic source(s).
202      */
203     private void unregisterMsgDispatcher() {
204         for (TopicSource source : TopicEndpointManager.getManager().getTopicSources(Arrays.asList(TOPIC))) {
205             source.unregister(msgDispatcher);
206         }
207     }
208
209     /**
210      * Start the xacmlpdp rest controller.
211      */
212     public void startXacmlRestController() {
213         if (isXacmlRestControllerAlive()) {
214             LOGGER.info("Xacml rest controller already running");
215         } else {
216             restServer.start();
217         }
218     }
219
220     /**
221      * Stop the xacmlpdp rest controller.
222      */
223     public void stopXacmlRestController() {
224         if (isXacmlRestControllerAlive()) {
225             restServer.stop();
226         } else {
227             LOGGER.info("Xacml rest controller already stopped");
228         }
229     }
230
231     public boolean isXacmlRestControllerAlive() {
232         return restServer.isAlive();
233     }
234 }