Support delta policy lists in xacml-pdp
[policy/xacml-pdp.git] / main / src / main / java / org / onap / policy / pdpx / main / comm / XacmlPdpUpdatePublisher.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.comm;
22
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Optional;
28 import java.util.stream.Collectors;
29 import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient;
30 import org.onap.policy.models.pdp.concepts.PdpStatus;
31 import org.onap.policy.models.pdp.concepts.PdpUpdate;
32 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
33 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
34 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
35 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
36 import org.onap.policy.pdpx.main.XacmlState;
37 import org.onap.policy.pdpx.main.rest.XacmlPdpApplicationManager;
38 import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class XacmlPdpUpdatePublisher {
43
44     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpUpdatePublisher.class);
45
46     private final TopicSinkClient client;
47     private final XacmlState state;
48     private final XacmlPdpApplicationManager appManager;
49
50     /**
51      * Constructs the object.
52      * @param client messages are published to this client
53      * @param state tracks the state of this PDP
54      * @param appManager application manager
55      */
56     public XacmlPdpUpdatePublisher(TopicSinkClient client, XacmlState state, XacmlPdpApplicationManager appManager) {
57         this.client = client;
58         this.state = state;
59         this.appManager = appManager;
60     }
61
62     /**
63      * Handle the PDP Update message.
64      *
65      * @param message Incoming message
66      */
67     public void handlePdpUpdate(PdpUpdate message) {
68
69         // current data
70         Map<ToscaConceptIdentifier, ToscaPolicy> deployedPolicies = policyToMap(appManager.getToscaPolicies().keySet());
71
72         // incoming data
73         Map<ToscaConceptIdentifier, ToscaPolicy> toBeDeployedPolicies = policyToMap(message.getPoliciesToBeDeployed());
74         List<ToscaConceptIdentifier> toBeUndeployedIds =
75                         Optional.ofNullable(message.getPoliciesToBeUndeployed()).orElse(Collections.emptyList());
76
77         // Undeploy policies
78         for (ToscaConceptIdentifier policyId: toBeUndeployedIds) {
79             ToscaPolicy policy = deployedPolicies.get(policyId);
80             if (policy == null) {
81                 LOGGER.warn("attempt to undeploy policy that has not been previously deployed: {}", policyId);
82             } else if (toBeDeployedPolicies.containsKey(policyId)) {
83                 LOGGER.warn("not undeploying policy, as it also appears in the deployment list: {}", policyId);
84             } else {
85                 appManager.removeUndeployedPolicy(policy);
86             }
87         }
88
89         var errorMessage = new StringBuilder();
90         // Deploy a policy
91         // if deployed policies do not contain the incoming policy load it
92         for (ToscaPolicy policy : toBeDeployedPolicies.values()) {
93             if (!deployedPolicies.containsKey(policy.getIdentifier())) {
94                 try {
95                     appManager.loadDeployedPolicy(policy);
96                 } catch (XacmlApplicationException e) {
97                     // Failed to load policy, return error(s) to PAP
98                     LOGGER.error("Failed to load policy: {}", policy, e);
99                     errorMessage.append("Failed to load policy: " + policy + ": "
100                             + e.getMessage() + XacmlPolicyUtils.LINE_SEPARATOR);
101                 }
102             }
103         }
104
105         // update the policy count statistic
106         var stats = XacmlPdpStatisticsManager.getCurrent();
107         if (stats != null) {
108             stats.setTotalPolicyCount(appManager.getPolicyCount());
109         }
110
111         PdpStatus status = state.updateInternalState(message, errorMessage.toString());
112         LOGGER.debug("Returning current deployed policies: {} ", status.getPolicies());
113
114         sendPdpUpdate(status);
115     }
116
117     private Map<ToscaConceptIdentifier, ToscaPolicy> policyToMap(Collection<ToscaPolicy> policies) {
118         if (policies == null) {
119             return Collections.emptyMap();
120         }
121
122         return policies.stream().collect(Collectors.toMap(ToscaPolicy::getIdentifier, policy -> policy));
123     }
124
125     private void sendPdpUpdate(PdpStatus status) {
126         // Send PdpStatus Change to PAP
127         if (!client.send(status)) {
128             LOGGER.error("failed to send to topic sink {}", client.getTopic());
129         }
130     }
131 }