3635a21a392cfe19abb8fb72035d93df3b2161af
[policy/xacml-pdp.git] / main / src / main / java / org / onap / policy / pdpx / main / XacmlState.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019, 2021-2022 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;
22
23 import java.time.Instant;
24 import java.util.Collections;
25 import org.apache.commons.lang3.StringUtils;
26 import org.onap.policy.common.utils.network.NetworkUtil;
27 import org.onap.policy.models.pdp.concepts.PdpMessage;
28 import org.onap.policy.models.pdp.concepts.PdpResponseDetails;
29 import org.onap.policy.models.pdp.concepts.PdpStateChange;
30 import org.onap.policy.models.pdp.concepts.PdpStatistics;
31 import org.onap.policy.models.pdp.concepts.PdpStatus;
32 import org.onap.policy.models.pdp.concepts.PdpUpdate;
33 import org.onap.policy.models.pdp.enums.PdpHealthStatus;
34 import org.onap.policy.models.pdp.enums.PdpResponseStatus;
35 import org.onap.policy.models.pdp.enums.PdpState;
36 import org.onap.policy.pdpx.main.rest.XacmlPdpApplicationManager;
37 import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager;
38 import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Current state of this XACML PDP.
44  */
45 public class XacmlState {
46     // The logger for this class
47     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlState.class);
48
49     /**
50      * Unique name for the xacml-pdp JVM, used in PdpStatus messages.
51      */
52     public static final String PDP_NAME = NetworkUtil.genUniqueName("xacml");
53
54     /**
55      * The application manager.
56      */
57     private final XacmlPdpApplicationManager appManager;
58
59     /**
60      * Records the current state of this PDP.
61      */
62     private final PdpStatus status;
63
64     /**
65      * Constructs the object, initializing the state.
66      */
67     public XacmlState(XacmlPdpApplicationManager appManager, String pdpGroupName, String pdpType) {
68         this.appManager = appManager;
69
70         this.status = new PdpStatus();
71         this.status.setName(PDP_NAME);
72         this.status.setPdpType(pdpType);
73         this.status.setState(PdpState.PASSIVE);
74         this.status.setPolicies(Collections.emptyList());
75         this.status.setPdpGroup(pdpGroupName);
76     }
77
78     /**
79      * Determines if this PDP should handle the given message.
80      *
81      * @param message message of interest
82      * @return {@code true} if this PDP should handle the message, {@code false} otherwise
83      */
84     public boolean shouldHandle(PdpMessage message) {
85         return message.appliesTo(status.getName(), status.getPdpGroup(), status.getPdpType());
86     }
87
88     /**
89      * Generates a new heart beat message.
90      *
91      * @return a new heart beat message
92      */
93     public synchronized PdpStatus genHeartbeat() {
94         // first, update status fields
95         status.setHealthy(XacmlPdpActivator.getCurrent().isAlive() ? PdpHealthStatus.HEALTHY
96             : PdpHealthStatus.NOT_HEALTHY);
97
98         PdpStatus heartbeat = new PdpStatus(status);
99         heartbeat.setStatistics(getStatistics());
100         return heartbeat;
101     }
102
103     /**
104      * Generates statistics to be used in a heart beat message.
105      *
106      * @return statistics for heart beat message
107      */
108     protected PdpStatistics getStatistics() {
109         XacmlPdpStatisticsManager stats = XacmlPdpStatisticsManager.getCurrent();
110         if (stats == null) {
111             LOGGER.warn("XacmlPdpStatisticsManager is null");
112             return null;
113         }
114         stats.setTotalPolicyCount(appManager.getPolicyCount());
115
116         PdpStatistics pdpStats = new PdpStatistics();
117         pdpStats.setPdpGroupName(this.status.getPdpGroup());
118         pdpStats.setPdpSubGroupName(this.status.getPdpSubgroup());
119         pdpStats.setTimeStamp(Instant.ofEpochSecond(this.status.getTimestampMs()));
120
121         pdpStats.setPolicyExecutedCount(stats.getPermitDecisionsCount() + stats.getDenyDecisionsCount());
122         pdpStats.setPolicyExecutedSuccessCount(stats.getPermitDecisionsCount());
123         pdpStats.setPolicyExecutedFailCount(stats.getDenyDecisionsCount());
124
125         pdpStats.setPolicyDeployCount(stats.getDeploySuccessCount() + stats.getDeployFailureCount());
126         pdpStats.setPolicyDeploySuccessCount(stats.getDeploySuccessCount());
127         pdpStats.setPolicyDeployFailCount(stats.getDeployFailureCount());
128
129         pdpStats.setPolicyUndeployCount(stats.getUndeploySuccessCount() + stats.getUndeployFailureCount());
130         pdpStats.setPolicyUndeploySuccessCount(stats.getUndeploySuccessCount());
131         pdpStats.setPolicyUndeployFailCount(stats.getUndeployFailureCount());
132         return pdpStats;
133     }
134
135     /**
136      * Updates the internal state based on the given message.
137      *
138      * @param message message from which to update the internal state
139      * @return a response to the message
140      */
141     public synchronized PdpStatus updateInternalState(PdpStateChange message) {
142         LOGGER.info("set state of {} to {}", this, message.getState());
143         status.setState(message.getState());
144
145         /*
146          * NOTE: Do NOT update group & subgroup as state-change requests do not set those
147          * fields to indicate new values; they only set them to do broadcasts to all PDPs
148          * within a group/subgroup.
149          */
150
151         PdpStatus status2 = makeResponse(message, "");
152
153         // start/stop rest controller based on state change
154         handleXacmlRestController();
155
156         // these fields aren't needed in the response, so clear them out to avoid sending
157         status2.setPolicies(null);
158
159         return status2;
160     }
161
162     /**
163      * Updates the internal state based on the given message. Assumes that the policies
164      * have already been updated within the application manager.
165      *
166      * @param message message from which to update the internal state
167      * @return a response to the message
168      */
169     public synchronized PdpStatus updateInternalState(PdpUpdate message, String errMessage) {
170         status.setPdpSubgroup(message.getPdpSubgroup());
171         status.setPolicies(appManager.getToscaPolicyIdentifiers());
172
173         return makeResponse(message, errMessage);
174     }
175
176     /**
177      * Updates the internal state to Terminated.
178      *
179      * @return the current PdpStatus with Terminated state
180      */
181     public synchronized PdpStatus terminatePdpMessage() {
182         LOGGER.info("set state of {} to {}", this, PdpState.TERMINATED);
183         status.setState(PdpState.TERMINATED);
184         return new PdpStatus(status);
185     }
186
187     /**
188      * Makes a response to the given message, based on the current state.
189      *
190      * @param message message for which the response should be made
191      * @param errMessage the error message to be sent to PAP
192      * @return a new response
193      */
194     private PdpStatus makeResponse(PdpMessage message, String errMessage) {
195         var resp = new PdpResponseDetails();
196
197         if (StringUtils.isBlank(errMessage)) {
198             resp.setResponseStatus(PdpResponseStatus.SUCCESS);
199         } else {
200             resp.setResponseStatus(PdpResponseStatus.FAIL);
201             resp.setResponseMessage(errMessage);
202         }
203         resp.setResponseTo(message.getRequestId());
204
205         var status2 = new PdpStatus(status);
206         status2.setResponse(resp);
207         return status2;
208     }
209
210     /**
211      * Manages the Xacml-Pdp rest controller based on the Xacml-Pdp State.
212      * Current supported states:
213      * ACTIVE  - rest service is running and handling requests
214      * PASSIVE - rest service is not running
215      */
216     private void handleXacmlRestController() {
217         if (status.getState() == PdpState.ACTIVE) {
218             LOGGER.info("State change: {} - Starting rest controller", status.getState());
219             XacmlPdpActivator.getCurrent().enableApi();
220         } else if (status.getState() == PdpState.PASSIVE) {
221             LOGGER.info("State change: {} - Stopping rest controller", status.getState());
222             XacmlPdpActivator.getCurrent().disableApi();
223         } else {
224             // unsupported state
225             LOGGER.warn("Unsupported state: {}", status.getState());
226         }
227     }
228 }