e7633674b675b41de97ccb0baafed0a4ef264907
[policy/xacml-pdp.git] / main / src / main / java / org / onap / policy / pdpx / main / startstop / XacmlPdpActivator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 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.nio.file.Paths;
24 import java.util.Arrays;
25 import java.util.Collections;
26 import java.util.Properties;
27 import lombok.Getter;
28 import lombok.Setter;
29 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
30 import org.onap.policy.common.endpoints.event.comm.TopicSource;
31 import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient;
32 import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClientException;
33 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
34 import org.onap.policy.common.parameters.ParameterService;
35 import org.onap.policy.common.utils.network.NetworkUtil;
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.models.pdp.enums.PdpState;
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.XacmlPdpRestServer;
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
68     // The parameters of this policy xacml pdp activator
69     private final XacmlPdpParameterGroup xacmlPdpParameterGroup;
70
71     /**
72      * The XACML PDP REST API server.
73      */
74     private XacmlPdpRestServer restServer;
75
76     /**
77      * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then
78      * dispatches them to appropriate listener.
79      */
80     private final MessageTypeDispatcher msgDispatcher;
81
82     /**
83      * Instantiate the activator for policy xacml pdp as a complete service.
84      *
85      * @param xacmlPdpParameterGroup the parameters for the xacml pdp service
86      * @param topicProperties properties used to configure the topics
87      */
88     public XacmlPdpActivator(final XacmlPdpParameterGroup xacmlPdpParameterGroup, Properties topicProperties) {
89         LOGGER.info("Activator initializing using {} and {}", xacmlPdpParameterGroup, topicProperties);
90
91         TopicEndpoint.manager.addTopicSinks(topicProperties);
92         TopicEndpoint.manager.addTopicSources(topicProperties);
93
94         XacmlPdpHearbeatPublisher heartbeat;
95         TopicSinkClient sinkClient;
96         final XacmlState state;
97
98         try {
99             XacmlPdpApplicationManager appmgr =
100                             new XacmlPdpApplicationManager(Paths.get(xacmlPdpParameterGroup.getApplicationPath()));
101             XacmlPdpApplicationManager.setCurrent(appmgr);
102
103             XacmlPdpStatisticsManager stats = new XacmlPdpStatisticsManager();
104             XacmlPdpStatisticsManager.setCurrent(stats);
105             stats.setTotalPolicyTypesCount(appmgr.getPolicyTypeCount());
106
107             state = new XacmlState(appmgr);
108
109             this.xacmlPdpParameterGroup = xacmlPdpParameterGroup;
110             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
111
112             sinkClient = new TopicSinkClient(TOPIC);
113             heartbeat = new XacmlPdpHearbeatPublisher(sinkClient, state);
114
115             /*
116              * since the dispatcher isn't registered with the topic yet, we can go ahead
117              * and register the listeners with it.
118              */
119             msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(),
120                             new XacmlPdpStateChangeListener(sinkClient, state));
121             msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(),
122                             new XacmlPdpUpdateListener(sinkClient, state, heartbeat, appmgr));
123
124         } catch (RuntimeException | TopicSinkClientException e) {
125             throw new PolicyXacmlPdpRuntimeException(e.getMessage(), e);
126         }
127
128         xacmlPdpParameterGroup.getRestServerParameters().setName(xacmlPdpParameterGroup.getName());
129
130         // @formatter:off
131         addAction("XACML PDP parameters",
132             () -> ParameterService.register(xacmlPdpParameterGroup),
133             () -> ParameterService.deregister(xacmlPdpParameterGroup.getName()));
134
135         addAction("Message Dispatcher",
136             this::registerMsgDispatcher,
137             this::unregisterMsgDispatcher);
138
139         addAction("topics",
140             TopicEndpoint.manager::start,
141             TopicEndpoint.manager::shutdown);
142
143         addAction("Terminate PDP",
144             () -> { },
145             () -> sendTerminateMessage(sinkClient, state));
146         // initial heart beats act as registration messages
147         addAction("Heartbeat Publisher",
148             heartbeat::start,
149             heartbeat::terminate);
150
151         addAction("Create REST server",
152             () -> restServer = new XacmlPdpRestServer(xacmlPdpParameterGroup.getRestServerParameters()),
153             () -> restServer = null);
154
155         addAction("REST server",
156             () -> restServer.start(),
157             () -> restServer.stop());
158
159         // @formatter:on
160     }
161
162     /*
163      * Method used to send a terminate message to the PAP.
164      */
165     private void sendTerminateMessage(TopicSinkClient sinkClient, XacmlState state) {
166         PdpStatus terminateStatus = state.terminatePdpMessage();
167         sinkClient.send(terminateStatus);
168     }
169
170     /**
171      * Get the parameters used by the activator.
172      *
173      * @return the parameters of the activator
174      */
175     public XacmlPdpParameterGroup getParameterGroup() {
176         return xacmlPdpParameterGroup;
177     }
178
179     /**
180      * Method to register the parameters to Common Parameter Service.
181      *
182      * @param xacmlPdpParameterGroup the xacml pdp parameter group
183      */
184     public void registerToParameterService(final XacmlPdpParameterGroup xacmlPdpParameterGroup) {
185         ParameterService.register(xacmlPdpParameterGroup);
186     }
187
188     /**
189      * Method to deregister the parameters from Common Parameter Service.
190      *
191      * @param xacmlPdpParameterGroup the xacml pdp parameter group
192      */
193     public void deregisterToParameterService(final XacmlPdpParameterGroup xacmlPdpParameterGroup) {
194         ParameterService.deregister(xacmlPdpParameterGroup.getName());
195     }
196
197     /**
198      * Registers the dispatcher with the topic source(s).
199      */
200     private void registerMsgDispatcher() {
201         for (TopicSource source : TopicEndpoint.manager.getTopicSources(Arrays.asList(TOPIC))) {
202             source.register(msgDispatcher);
203         }
204     }
205
206     /**
207      * Unregisters the dispatcher from the topic source(s).
208      */
209     private void unregisterMsgDispatcher() {
210         for (TopicSource source : TopicEndpoint.manager.getTopicSources(Arrays.asList(TOPIC))) {
211             source.unregister(msgDispatcher);
212         }
213     }
214 }