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